jackpipe
jackpipe

Reputation: 981

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.

Upvotes: 45

Views: 40529

Answers (6)

woto
woto

Reputation: 3077

In 2021 it works as expected 😏

click_link('...', href: '...')
click_link('...')
click_link(href: '...')

Upvotes: 17

jmarceli
jmarceli

Reputation: 20162

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.

Upvotes: 8

diabolist
diabolist

Reputation: 4099

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

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

Upvotes: 23

vanboom
vanboom

Reputation: 1332

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

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

Upvotes: 0

jackpipe
jackpipe

Reputation: 981

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

Upvotes: 11

jvnill
jvnill

Reputation: 29599

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

Upvotes: 46

Related Questions