Greg Stone
Greg Stone

Reputation: 95

Clicking on the second of the two identical elements in capybara

I am writing the test automaton code for a system and the dev team presented me the following html:

<div id="someId">
  <div class="classA">
    <button class="classB">
  </div>
  <div class="classA">
    <button class="classB">
  </div>
</div>

Now the question is: Is it possible to click exclusively on the SECOND button? If so - how?

Upvotes: 2

Views: 1684

Answers (2)

HargrimmTheBleak
HargrimmTheBleak

Reputation: 2167

I would not rely on the order of elements returned by all. I remember running into issues with it in the past, see e.g. this issue. Instead I'd use a selector, something like this:

find("#someId div.classA:nth-child(1) button.classB").click

(IIRC they are zero-indexed)

Upvotes: 1

Nikola
Nikola

Reputation: 827

If I understand you right, you're click on links styled as buttons. You can use this step definition

Then(/^I click the (\d+) instance of link "(.*?)"$/) do |instance, link|
   page.all('a', :text => "#{link}")[instance.to_i - 1].click    
end

Upvotes: 3

Related Questions