1

I am using capybara to click a checkbox, however it can't seem to find it no matter what I do. I am able to correctly find both the span and the label inside the span, but not the input I actually need.

Here is the checkbox

<span class="checkbox tos">
  <input id="agreement" name="agreement" onclick="agreeValidate();" type="checkbox" value="false">
  <label for="agreement">I accept the <a href="http://www.dev.com:3000/terms" target="_blank">Terms of Use</a>, <a href="http://www.dev.com:3000/privacy" target="_blank">Privacy Policy</a>, and am at least 13 years old</label>
</span>

And here is some of the things I have tried

page.check('agreement')
find(:css, '#agreement').set(true)
find('#agreement').set(true)
find('#agreement').click

However, they all give me the same error

Unable to find css "#agreement" (Capybara::ElementNotFound)

I also am wondering will any of these methods fire off the onclick method, when the checkbox is clicked? I feel like find(:css, '#agreement').set(true) will not trigger the onclick event. However, I am not sure about the rest.

EDIT** I have also tried selecting the element through xpath. Here are the various things I have found out

find(:xpath, '//*[@id="registration"]/span[2]')

This is able to find the span element no problem

find(:xpath, '//*[@id="registration"]/span[2]/input')

This cant find the element I need, but this xpath correctly selects the element in chromes console

find(:xpath, '//*[@id="agreement"]')

This cant find the element I need, but the xpath selects the element in chromes console

find(:xpath, '//*[@id="registration"]/span[2]/label')

This is able to find the label element in the span with no problem.

user2158382
  • 4,430
  • 12
  • 55
  • 97

1 Answers1

1

You can use the cheatsheet for Capybara here: http://learn.thoughtbot.com/test-driven-rails-resources/capybara.pdf

It's a bad idea to interact with form through CSS. A better way to do something like this:

check 'I accept cool agreement'
click_button 'Submit'

So you do not need to know ID of element or class. Just use what users can see on page.

Alex Pan
  • 4,341
  • 8
  • 34
  • 45
Pavel Tkackenko
  • 963
  • 7
  • 20
  • 2
    Could you justify your opinion (with examples/reasons) for why it is a bad idea to interact with a form through classes/ids? At least in my experience, these are much less likely to change than the text of the question. – pixelearth Oct 15 '16 at 17:50