Capybara::ElementNotFound: Unable to find css “#transaction_form”
我正在学习使用rspec和capybara编写功能规范。我正在尝试为处理事务的应用程序编写规范。我的事务控制器如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |
它的视图如下/ transactions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <%= form_for(@transaction, id: 'transaction_form', :html => {class: 'form-horizontal', role: 'form'}) do |t| %> <%= t.label :amount %> <%= t.text_field :amount, class: 'form-control', placeholder: 'Enter amount', autofocus: true %> <%= t.label :transaction_type %> <%= t.select :transaction_type, Transaction.transaction_types.keys %> <%= t.submit 'Submit', class: 'btn btn-primary btn' %> <% end %> |
我添加了
规范代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 7 8 | 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" |
我想念的是什么?如果我直接使用
此外,仅当用户登录时才会显示/ transactions / new页。那么这还会影响交易规范吗?如果是,那应该怎么办?
请帮助。预先感谢。
如果要与之交互的页面仅在用户登录后才可见,那么您需要登录该用户。这也意味着您需要在登录前创建要登录的用户。测试开始。通常,这可以通过使用Rails固定装置或工厂(例如factory_bot gem)来完成。创建用户后,您将需要登录,就像访问登录页面并输入用户的用户名和密码一样简单。如果您使用的是gem进行身份验证,它可能会提供一种测试模式,该模式允许绕过实际访问登录页面以加快测试速度(即devise提供了此功能-https://github.com/plataformatec/devise/ Wiki /操作方法:使用水豚进行测试)