How to check a checkbox in capybara?
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
. I'm not sure what to do, as I have in fact same ID with different values
Here is the code:
<input id="cityID" type="checkbox" style="text-align: center; opacity: 0;" value="61" name="cityID">
<input id="cityID" type="checkbox" style="text-align: center; opacity: 0;" value="62" name="cityID">
<input id="cityID" type="checkbox" style="text-align: center; opacity: 0;" value="63" name="cityID">
Solution 1:
I found the following worked for me:
# Check
find(:css, "#cityID[value='62']").set(true)
# Uncheck
find(:css, "#cityID[value='62']").set(false)
Solution 2:
It's better not to create multiple elements with the same id, so that (and not only for that) you can easily check/uncheck a checkbox with elegant
check 'cityID'
uncheck 'cityID'
If one can not avoid multiple elements with the same id and still needs to check a checkbox with certain value, he can do so with
find(:css, "#cityID[value='62']").set(true)
find(:css, "#cityID[value='62']").set(false)
More information on capybara input manipulations can be found here
Solution 3:
When running capybara test, you got the page
object. This you can use to check/uncheck any checkboxes. As @buruzaemon already mentioned:
to find and check a checkbox by name, id, or label text.
So lets assume you got a checkbox in your html like:
<label>
<input type="checkbox" value="myvalue" name="myname" id="myid">
MyLabel
</label>
You could check this with:
page.check('myid')
page.check('MyLabel')
page.check('myname')
Uncheck is the same just use page.uncheck
method.
Solution 4:
I think you may have to give unique id
s 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.
Solution 5:
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'