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

时间:2018-11-14 11:24:18

标签: ruby-on-rails rspec capybara

我正在学习使用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页。这是否也会影响交易规范?如果是,那应该怎么办?

请帮助。预先感谢。

1 个答案:

答案 0 :(得分:0)

如果要与之交互的页面仅在用户登录后才可见,那么您需要登录该用户。这也意味着您需要在测试之前创建要登录的用户。开始。通常,这可以使用Rails固定装置或工厂(例如factory_bot gem)来完成。创建用户后,您需要登录他们,就像访问登录页面并输入用户名和密码一样简单。如果您使用的是gem进行身份验证,它可能会提供一种测试模式,该模式允许绕过实际访问登录页面以加快测试速度(例如,devise提供此功能-https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara