如何在使用simple_form时检查Capybara测试中的复选框

时间:2016-01-24 21:35:25

标签: capybara rspec-rails

尝试在简单页面中测试某些功能,并且在使用page.check时出现此错误:

    Failures:

  1) searching for stores serving a taco and a sauce: Adobada tacos with Chile de Arbol sauce
     Failure/Error: page.check 'Adobada'

     Capybara::ElementNotFound:
       Unable to find checkbox "Adobada"
     # ./spec/views/store_search_spec.rb:8:in `block (2 levels) in <top (required)>'

这是我的HTML:

<%= simple_form_for :stores, url: stores_path, method: :get do |f| %>

  <%= f.label :tacos, 'Select Tacos to Find: ', class: 'label' %>
  <div class='taco-select checkboxes'>
    <%= f.collection_check_boxes :tacos, Taco.order(:name), :id, :name,
      :include_hidden => false, :item_wrapper_class => 'checkbox_container' %>
  </div>

  <%= f.label :salsa, 'Select Sauces to Find: ', class: 'label' %>
  <div class='salsa-select checkboxes'>
    <%= f.collection_check_boxes :salsas, Salsa.order(:name), :id, :name,
      :include_hidden => false, :item_wrapper_class => 'checkbox_container' %>
  </div>

  <%= f.submit 'Search!' %>

<% end %>

这是我的考验:

require 'rails_helper'

feature 'searching for stores', %(serving a taco and a sauce:) do

  scenario 'Adobada tacos with Chile de Arbol sauce' do
    visit root_path

    page.check 'Adobada'
    page.check 'Chile de Arbol'

    click_button 'Search!'

    expect(page).to have_content "Store"
    expect(page).to have_content 'City'

  end
end

我想测试一下,当某些复选框设置为true时,会在页面中呈现某个内容。 不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:7)

试试这些,它们应该适合你:

find(:css, "#YOUR_CHECKBOX_ID").set(true)

page.check('YOUR_CHECKBOX_ID')

或只是

find('THE CSS SELECTOR OF YOUR CHECKBOX').click
find(:xpath, 'THE XPATH OF YOUR CHECKBOX').click

答案 1 :(得分:3)

您不必使用ID来选中复选框。您只需使用复选框上的标签即可。假设你有一个像这样的复选框

<label for="...">
  <input type="checkbox" name="...">Something</label>

你这样在水豚中检查它

it "" do
  page.check 'Something'
end

关于此的官方文档可以找到here