Capybara::ElementNotFound: 无法找到 css“#transaction_form”

Capybara::ElementNotFound: Unable to find css "#transaction_form"

我正在学习使用 rspec 和水豚编写功能规范。我正在尝试为处理事务的应用程序编写规范。我的事务控制器如下:

  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/new:

<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页面只有在用户登录后才会显示。那么这是否也会影响交易规范?如果是,那应该怎么办?

请帮忙。提前致谢。

如果您要与之交互的页面仅在用户登录时可见,那么您需要让用户登录。这也意味着您需要先创建要登录的用户测试开始。通常这将使用 Rails 固定装置或工厂(如 factory_bot gem). Once you have create the user then you'll need to log them in, which can be as simple as visiting the login page and entering the users username and password. If you're using a gem for authentication it may provide a test mode which allows for bypassing actually visiting the login page in order to speed up tests (ie. devise provides this - https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

来完成