Rails/Capybara: How to click a link in a table row

2019-04-05 17:15发布

问题:

I have an app that does not assign unique IDs to table cells. Given unique text in column 1, a manage link in column 2, and a delete link in column 3, how do I tell capybara to click the manage link in the same row that contains the text 'Foo'?

Foo   manage  delete
Bar   manage  delete

I see how to use find('tr', text: "Foo") when used with a .should clause. And I see how to click a link that contains the text 'manage'. But I do not see how to combine them tofind a row, and within that row, click a link.

回答1:

I've tested this and it should work:

find(:xpath, "//tr[td[contains(.,'Foo')]]/td/a", :text => 'manage').click

What this says is, find the row with a column which contains the text 'Foo', and click on the link in a column in the same row with a text 'manage'.

If you don't care where 'Foo' appears (i.e. could be anywhere in the row), then you can do this:

find(:xpath, "//tr[contains(.,'Foo')]/td/a", :text => 'manage').click


回答2:

Another example:

When(/^I delete the Book with the Title "(.*?)"$/) do |title|
  find('tr', text: title).click_link("Delete")
end