How to check a checkbox in capybara?

前端 未结 13 1854
灰色年华
灰色年华 2020-11-30 23:34

I\'m using Rspec and Capybara.

How can I write a step to check a checkbox? I\'ve tried check by value but it can\'t find my checkbox<

相关标签:
13条回答
  • 2020-11-30 23:53

    I know this is an older question, but I have been working through this myself, and having tried all of the above, this is what finally worked for me:

    find("input[type='checkbox'][value='#{cityID.id}']").set(true)
    

    Hope this is helpful to someone. I am using Capybara 2.4.4.

    0 讨论(0)
  • 2020-11-30 23:57

    I think you may have to give unique ids to your form elements, first of all.

    But with regards to Capybara and checkboxes, the Capybara::Node::Actions#check instance method will allow you to find and check a checkbox by name, id, or label text.

    0 讨论(0)
  • 2020-11-30 23:59

    If the box is associated with text, e.g. 'Option 3', then as of capybara 3.0.3 you can just do

    check 'Option 3'
    
    0 讨论(0)
  • 2020-11-30 23:59

    you can also use :xpath instead of :css if you have some problems finding it.

    find(:xpath , '//*[@id="example"]').set(true)

    on Chrome (and surely other browsers), you can "inspect element" and then by right clicking on the element you are interested in, there is 'copy xpath' if you don't know what xpath was, now you do.

    0 讨论(0)
  • 2020-12-01 00:02

    .set(true) didn't work for me so I had to call .click:

    find(...).click

    0 讨论(0)
  • 2020-12-01 00:03

    You can also check that all the checkboxes are not checked with this example.

    all('input[type=checkbox]').each do |checkbox| checkbox.should_not be_checked end

    0 讨论(0)
提交回复
热议问题