我正在学习使用rspec和capybara编写特性规范。我试图为处理事务的应用程序编写规范。我的事务控制器如下:
def new
@transaction = Transaction.new
end
def create
transaction = Transaction.new(transaction_params)
transaction.account = current_account
if transaction.save && transaction.account.save
flash[:success] = 'Transaction successfull'
else
flash[:danger] = 'Insufficient balance'
end
redirect_to root_path
end委员会认为,以下事务/新事务:
<div class = 'row'>
<div class = 'col-xs-12'>
<%= form_for(@transaction, id: 'transaction_form', :html => {class: 'form-horizontal', role: 'form'}) do |t| %>
<div class = 'form-group'>
<div class = 'control-label col-sm-2'>
<%= t.label :amount %>
</div>
<div class = 'col-sm-8'>
<%= t.text_field :amount, class: 'form-control', placeholder: 'Enter amount', autofocus: true %>
</div>
</div>
<div class = 'form-group'>
<div class = 'control-label col-sm-2'>
<%= t.label :transaction_type %>
</div>
<div class = 'col-sm-8'>
<%= t.select :transaction_type, Transaction.transaction_types.keys %>
</div>
</div>
<div class = 'form-group'>
<div class = 'col-sm-offset-2 col-sm-10'>
<%= t.submit 'Submit', class: 'btn btn-primary btn' %>
</div>
</div>
<% end %>我为表单添加了id: transaction_form以避免不明确的错误。规范代码如下:
RSpec.feature 'Transactions', type: :feature do
context 'create new transaction' do
scenario 'should be successfull' do
visit new_transaction_path
within('#transaction_form') do
fill_in 'Amount', with: '60'
end
click_button 'Submit'
expect(page).to have_content('Transaction successfull')
end
end
end但是,在运行此规范时,我得到的错误如下:
1) Transactions create new transaction should be successfull
Failure/Error:
within('#transaction_form') do
fill_in 'Amount', with: '60'
end
Capybara::ElementNotFound:
Unable to find css "#transaction_form"我错过了什么?如果我直接使用form,它将抛出歧义错误,因为它从不同的文件中获取相同的元素。这个代码有什么问题?
此外,只有当用户登录时才会显示/transactions/new页面。那么,这也会影响事务规范吗?如果是,那该怎么办呢?
请帮帮忙。提前谢谢。
发布于 2018-11-14 17:24:04
如果只在用户登录时才能看到要与其交互的页面,则需要将用户登录。这也意味着您需要在测试开始之前创建要登录的用户。通常使用Rails固定装置或工厂(如bot gem)来完成。一旦您创建了用户,那么您就需要登录它们,这可以简单的访问登录页面并输入用户用户名和密码。如果您使用gem进行身份验证,它可能提供一种测试模式,允许绕过实际访问登录页面,以加快测试(即。设计提供这个- https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara)
https://stackoverflow.com/questions/53299090
复制相似问题