BvuRVKyUVlViVIc7
BvuRVKyUVlViVIc7

Reputation: 11811

Select elements from checkbox-group with Capybara

I have a lot of rows like this:

<input id="car_ids_" name="car_ids[]" value="142" type="checkbox"> Car 142
<input id="car_ids_" name="car_ids[]" value="143" type="checkbox"> Car 143
<input id="car_ids_" name="car_ids[]" value="144" type="checkbox"> Car 144
<input id="car_ids_" name="car_ids[]" value="145" type="checkbox"> Car 145

I want this behaviour since i saw it in this railscast: http://railscasts.com/episodes/165-edit-multiple?view=asciicast

When i test myself, it works, but when I try to select some elements with Capybara, i dont know how?

before(:each) do
  check "car_ids_:first"
  check "car_ids_:last"
end

I get always

Capybara::ElementNotFound:
       cannot check field, no checkbox with id, name, or label 'car_ids_:first' found

Can you help me how this works? I want to select f.e. the second and the third element?

UPDATE:

  find(:css, "#car_ids_[value='#{@car1.id}']").set(true)
  => find(:css, "#car_ids_[value='#{@car1.id}']").checked?
  ==> "checked"
  find(:css, "#car_ids_[value='#{@car2.id}']").set(nil)
  => find(:css, "#car_ids_[value='#{@car1.id}']").checked?
  ==> nil
  find(:css, "#car_ids_[value='#{@car3.id}']").set(true)
  => find(:css, "#car_ids_[value='#{@car1.id}']").checked?
  ==> "checked"

  select("Deactivate", :from => "car_action")

  click_button "Submit"

  page.body.should have_content "Updated cars!"

  @user.cars[0].active?.should == true
  @user.cars[1].active?.should == false
  @user.cars[2].active?.should == true

But in the end, the checkbox values are not passed to the controller! I dont know why.... The checkboxes seem checked (but if i open the page with save_and_open_page they are also not checked?)

Upvotes: 0

Views: 4630

Answers (1)

HargrimmTheBleak
HargrimmTheBleak

Reputation: 2167

The simplest way is to tell capybara to check the boxes by their labels. If you have the @cars collection at your disposal, you can do something like this:

[@cars[1], @cars[2]].each do |car|
  check("Car #{car.id}")
end

EDIT

Based on your comment below, if you want to specifically access 2nd and 3rd elements without regard to what collection items they refer to, you can wrap your inputs in a div with some id (to narrow the selector scope), e.g. car-checkboxes, and then do this:

find(:css, "#car-checkboxes input:nth-child(2)").click

or

find(:css, "#car-checkboxes input:nth-child(2)").set(true)

Upvotes: 1

Related Questions