Reputation: 461
I'm having quite a bit of trouble checking a terms of service box from simple_form in my capybara/rspec test.
Here is my validation:
validates :terms_of_service, acceptance: true, allow_nil: false
If I remove allow_nil: false then the specs all pass even if the box isn't checked. If I leave it, the validation causes the specs to fail.
Here is the code creating the form/checkbox:
= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', terms_of_service_path, :target => "_blank"}".html_safe
= f.check_box :terms_of_service
The resulting html:
<label for="candidate_terms_of_service">I agree to the <a href="/terms_of_service" target="_blank">Terms of Service</a></label>
<input name="candidate[terms_of_service]" type="hidden" value="0">
<input id="candidate_terms_of_service" name="candidate[terms_of_service]" type="checkbox" value="1">
My attempts in my test which I've tried individually:
page.find_by_id("candidate_terms_of_service").check
find(:xpath, "//*[@id='candidate_terms_of_service']").set(true)
find(:css, "#candidate_terms_of_service").set(true)
check 'candidate[terms_of_service]'
check 'I agree to the Terms of Service'
find('#candidate_terms_of_service').check
And resulting failure:
Failure/Error: let(:candidate) { create(:candidate) }
ActiveRecord::RecordInvalid:
Validation failed: Terms of service must be accepted
How do I check this box?
Upvotes: 0
Views: 569
Reputation: 5529
This particular simple_form field gave me a lot of grief, and while I found several different ways mentioned to query and set it, none of them worked (some mentioned in this issue, others from Capybara issues).
I found the following to actually work with a simple_form boolean with RSpec:
find(:xpath, "//label[@for='candidate_terms_of_service']").click
For the sake of completeness considering the different webdrivers and total solutions given, here are the other solutions found but resulted in invalid selector errors. The input selector would actually error about the inability to check simple_form's default hidden input; this error makes sense, the label is the visible and top-most element.
find('#active_form_terms_of_service').set(true)
# or select by label
find('label[for=active_form[terms_of_service]').click
# and select by label and value if multiple boxes
# with the same ID (not sure why this would happen)
find("label[value='1']").click
# or select the input with xpath
find(:xpath, "//input[value='1']").set(true)
Upvotes: 1