39

我在请求规范中有以下测试:

page.should have_link('Edit user', :href => edit_users_path(@user))

这将检查索引视图中的特定用户是否具有编辑链接。我想单击相同的链接,例如:

click_link('Edit user', :href => edit_users_path(@user))

不幸的是 click_link 不接受选项。

有没有一种好方法可以做到这一点,这似乎是一个相当明显的用例?

我应该在表中包含#id<tr>还是<td>执行以下操作:

within(#user_id)
  click_link 'Edit user'
end

我不想为了让测试正常工作而修改视图。

4

6 回答 6

45

你可以使用查找find(:xpath, "//a[@href='/foo']").click

于 2013-02-19T12:57:14.867 回答
20

您可以使用 Capybara 的低级界面来执行此操作。尝试:

find("a[href='#{edit_users_path}']").click
于 2014-12-09T14:02:00.660 回答
11

我最终在spec/support/selectors.rb

module Selectors
  Capybara.add_selector(:linkhref) do
    xpath {|href| ".//a[@href='#{href}']"}
  end
end

然后在我使用的测试中

find(:linkhref, some_path).click
于 2013-03-13T08:09:53.373 回答
7

根据@jackpipe 的回答(以及我以前的经验),我构建了自己的 Capybara 选择器,这里是辅助模块(spec/support/selectors.rb)的代码:

module Selectors
  # find(:href, 'google.com')
  Capybara.add_selector(:href) do
    xpath {|href| XPath.descendant[XPath.attr(:href).contains(href)] }
  end
end

使用示例:

find(:href, 'google')

有什么不同?

好吧,这将找到任何包含“google”的链接。以下将匹配:

www.google.com
http://google.com
fonts.google.com
something.google.inside.com

更重要的是,它只会在后代选择器中搜索,因此例如within('header') { find(:href, 'google').click }可以正常工作。

于 2015-04-01T22:25:35.550 回答
4

在 2021 年,它按预期工作

click_link('...', href: '...')
click_link('...')
click_link(href: '...')
于 2021-06-07T18:36:02.917 回答
0

将第一个参数留空似乎对我有用......

page.should have_link("", :href=>edit_comment_path(@comment))
于 2013-12-08T22:44:09.623 回答