Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capybara click_link with :href match

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.

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:

within(#user_id)
  click_link 'Edit user'
end

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

like image 246
jackpipe Avatar asked Feb 19 '13 12:02

jackpipe


5 Answers

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

like image 197
jvnill Avatar answered Oct 04 '22 18:10

jvnill


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

find("a[href='#{edit_users_path}']").click
like image 42
diabolist Avatar answered Oct 04 '22 17:10

diabolist


I ended up adding a helper module in 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
like image 28
jackpipe Avatar answered Oct 04 '22 16:10

jackpipe


Based on @jackpipe answer (and my previous experience) I build my own Capybara selector, here is the code for helper module (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.

like image 45
jmarceli Avatar answered Oct 04 '22 18:10

jmarceli


In 2021 it works as expected 😏

click_link('...', href: '...')
click_link('...')
click_link(href: '...')
like image 34
woto Avatar answered Oct 04 '22 17:10

woto