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.
you can use find find(:xpath, "//a[@href='/foo']").click
You can use Capybara's lower level interface to do this. Try:
find("a[href='#{edit_users_path}']").click
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
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.
In 2021 it works as expected 😏
click_link('...', href: '...')
click_link('...')
click_link(href: '...')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With