L.D
L.D

Reputation: 1329

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.

Upvotes: 3

Views: 8328

Answers (2)

fabdurso
fabdurso

Reputation: 2444

Try with these, they should work for you:

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

or

page.check('YOUR_CHECKBOX_ID')

or simply

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

Upvotes: 7

MilesStanfield
MilesStanfield

Reputation: 4649

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

Upvotes: 2

Related Questions