2013-02-19 62 views
29

我有一个请求规范下列测试:水豚click_link用:HREF匹配

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

这就验证了在索引视图的特定用户具有编辑链接。 我想点击相同的链接,喜欢的东西:

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

可惜click_link不接受选项。

有没有一个很好的方法来做到这一点,它似乎是一个相当明显的用例?

我应该是包括在表<tr><td>一个#ID和做这样的事情:

within(#user_id) 
    click_link 'Edit user' 
end 

我宁愿不与视图鼓捣只是为了让测试工作。

回答

38

您可以使用发现find(:xpath, "//a[@href='/foo']").click

+1

看起来很惭愧,必须明确地下降到html级别,但这个作品,谢谢! – jackpipe 2013-02-20 03:25:27

+1

这是给水豚:: ElementNotFound:错误.... – 2013-12-09 07:07:10

11

我结束了在我使用的测试

find(:linkhref, some_path).click 
+0

你如何处理“有”?即page.should have_linkhref(...) – vanboom 2013-12-08 22:26:49

+0

真的好主意!感谢分享。 – Starkers 2014-02-01 01:52:38

+0

@vanboom你可以定义该方法def have_linkhref(href) Capybara :: RSpecMatchers :: HaveSelector.new(:linkhref,href) end使用像expect(page).to have_linkhref url – icem 2014-06-16 14:20:42

0

离开的第一个参数的空白似乎工作在spec/support/selectors.rb

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

把帮助模块,然后对我来说...

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

OP请求如何*点击*链接。他说,“应该有链接”工作 – 2014-01-28 13:45:59

12

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

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

基于@jackpipe答案(和我以前的经验)我建立我自己的水豚选择,这里是辅助模块的代码(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') 

有什么区别?

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

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

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

+0

谢谢,这真的很好。 – 2016-03-22 12:56:45