9

I'd like to find the first instance of a checkbox using the capybara dsl. Anyone know how to do that?

I thought perhaps it'd be this, but it didn't work:

find('input:first', :type => 'checkbox')

3 Answers 3

19

Assuming Capybara.default_selector is set to CSS then:

find("input[type='checkbox']")

If you're using XPath it will be different.

Update (June 2013): as @tmg points out, the behaviour for Capybara 2 has changed.

3
  • Will this find the very FIRST checkbox?
    – btelles
    May 19, 2011 at 1:28
  • 2
    Yes. Alternatively: all("input[type='checkbox']").first
    – Andy Waite
    May 19, 2011 at 2:01
  • 11
    In Capybara 2 find will raise Capybara::Ambiguous if more than one element matches. Instead use: first("input[type='checkbox']") or find a more unique locator to use with find. See: first
    – tgf
    Mar 5, 2013 at 18:20
11

Just to point out tmg's right way to find the first checkbox

first("input[type='checkbox']")

If you want to find n-th checkbox (25-th for example):

find(:xpath, "(//input[@type='checkbox'])[25]")

But it's often better to use within to narrow your searching area

within 'div.div_class' do
  find("input[type='checkbox']")
end
2

The least flaky way to find the first checkbox could be:

find("input[type='checkbox']", match: :first)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.