Search code examples
capybararspec-rails

How to check a check box in Capybara test when using simple_form


Trying to test some functionality in a simple page and I am getting this error when using 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)>'

Here is my 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 %>

And this is my test:

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

I would like to test that when some checkboxes are set to true a certain content is rendered in the page. Don't know how to fix this.


Solution

  • You don't have to use an ID to check a checkbox. You can just use the label on the checkbox. Say you have a checkbox like this

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

    You 'check' it in capybara like so

    it "" do
      page.check 'Something'
    end
    

    Official docs on this can be found here