How to click first link in list of items after upg

2019-01-21 02:23发布

How to click first link in that case:

<div class="item">
  <a href="/agree/">Agree</a>
</div>
<div class="item">
  <a href="/agree/">Agree</a>
</div>
within ".item" do
  first(:link, "Agree").click
end

and I get this error:

Capybara::Ambiguous:
  Ambiguous match, found 2 elements matching css ".item"

And without the within I get this error:

Failure/Error: first(:link, "Agree").click
NoMethodError:
  undefined method `click' for nil:NilClass

6条回答
2楼-- · 2019-01-21 02:49

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.

查看更多
唯我独甜
3楼-- · 2019-01-21 02:49
迷人小祖宗
4楼-- · 2019-01-21 02:50

Simple you can use:

$('.item').find('a').first().click();
查看更多
Luminary・发光体
5楼-- · 2019-01-21 03:04

Since first() doesn't always wait, perhaps this is useful:

expect(page).to have_css("selector")                               
first("selector").click
查看更多
迷人小祖宗
6楼-- · 2019-01-21 03:11

This phrasing also works:

within first(".item") do
  click_link "Agree"
end
查看更多
beautiful°
7楼-- · 2019-01-21 03:13

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
查看更多
登录 后发表回答