How to click first link in list of items after upgrading to Capybara 2.0?

You can just use:

first('.item').click_link('Agree')

or

first('.item > a').click

(if your default selector is :css)


Code in your question doesn't work as:

within ".item" do
  first(:link, "Agree").click
end

is equivalent to:

find('.item').first(:link, "Agree").click

Capybara finds several .item's so it raises an exception. I consider this behavior of Capybara 2 very good.


Try the following:

within ".item" do
  click_link("Agree", :match => :first)
end

Sources:

  • http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Actions#click_link-instance_method
  • https://github.com/jnicklas/capybara#strategy

Xpath can address the element. I'm not very good with it yet, but something like //div[@class='active'][1]/a

That may or may not work, but the point is that xpath can address an array of matches and pull out a particular one. You should be able to match with this.

A working example example from one of my projects:

within page.find("div.panel", text: /Proposals/) do
  within page.find('tr', text: /Foo/) do
    page.should have_xpath('td[3]', text: @today)
  end
end

This phrasing also works:

within first(".item") do
  click_link "Agree"
end