Drew Verlee
Drew Verlee

Reputation: 1900

Rails: How to use Capybara to test a link's href-value without caring about the text?

Capybara provides a useful method to check a link:

have_link

which as far as I can tell can be used like:

have_link("link_text", :href => "actual link")

However, I don't care about the link_text, rather I just want to check href (as linking the test to the text is more brittle). If I only want to check the href this would be a view test.

How do I use Capybara to check the href without needing to check the text? Maybe i can use regex?

[edit] changed wording based on answer below

Upvotes: 34

Views: 34562

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49950

To find a link based on just its href using capybara you could do

link = page.find(:css, 'a[href="actual link"]')

or if you're looking to assert that the element exists

page.assert_selector(:css, 'a[href="actual link"]')

or - if using RSpec

expect(page).to have_selector(:css, 'a[href="actual link"]')

Since have link by default searches for substrings in the link text you can also do

expect(page).to have_link(nil, href: 'actual link')

or

page.assert_selector(:link, nil, href: 'actual link')

Upvotes: 58

Fabio
Fabio

Reputation: 19216

While looking to the same answer I found out that it's possible to pass options to first argument of have_link because it's implementation is:

# RSpec matcher for links
# See {Capybara::Node::Matchers#has_link?}
def have_link(locator=nil, options={}, &optional_filter_block)
  locator, options = nil, locator if locator.is_a? Hash
  HaveSelector.new(:link, locator, options, &optional_filter_block)
end

So if you don't care about link text you can safely omit first parameter and do this (RSpec syntax):

expect(page).to have_link(href: 'some url')
# or even
expect(page).to have_link(href: /some url regexp/)

Upvotes: 12

Related Questions