Ruby-on-rails 水豚 click_link 与 :href 匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14957981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:25:26  来源:igfitidea点击:

capybara click_link with :href match

ruby-on-railscapybara

提问by Hymanpipe

I have the following test in a request spec:

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

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

This checks that a specific user in an index view has an edit link. I would like to click the same link, with something like:

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

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

Unfortunately click_link doesn't accept options.

不幸的是,click_link 不接受选项。

Is there a good way to do this, it seems like a fairly obvious use case?

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

Should I be including an #id in the table <tr>or <td>and doing something like:

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

within(#user_id)
  click_link 'Edit user'
end

I'd prefer not to tinker with the view just to get the tests to work.

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

回答by jvnill

you can use find find(:xpath, "//a[@href='/foo']").click

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

回答by diabolist

You can use Capybara's lower level interface to do this. Try:

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

find("a[href='#{edit_users_path}']").click

回答by Hymanpipe

I ended up adding a helper module in spec/support/selectors.rb

我最终添加了一个辅助模块 spec/support/selectors.rb

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

Then in the tests I use

然后在我使用的测试中

find(:linkhref, some_path).click

回答by jmarceli

Based on @Hymanpipe answer (and my previous experience) I build my own Capybara selector, here is the code for helper module (spec/support/selectors.rb):

根据@Hymanpipe 的回答(以及我以前的经验),我构建了自己的 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

Usage example:

用法示例:

find(:href, 'google')

What's the difference?

有什么不同?

Well this will find any link which contains 'google'. The following will match:

那么这将找到任何包含“谷歌”的链接。以下将匹配:

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

What's more it will search only among descendant selectors so e.g. within('header') { find(:href, 'google').click }will work correct.

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

回答by vanboom

Leaving the first argument blank seems to work for me...

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

page.should have_link("", :href=>edit_comment_path(@comment))