2013-02-19 61 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