alexin
alexin

Reputation: 243

Find all links that have an href that begins with a specific text

I need to find all links on the page where the href begins with ../items/. For example:

<a href="../items/some-link">Some link title</a>
<a href="../other-link">Other link title</a>
<a href="../items/some-link-2">Some link title 2</a>

I tried the following Regexp, but it is not working:

review_links = page.find_link('a')[:href] == '%r{^../items/\w+}'

What am I doing wrong?

Upvotes: 2

Views: 2052

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49900

The :link selector takes an :href option that accepts a regex to match against. So if you're looking for a single result you could do

page.find_link(nil, href: /regex to match against/) 

in Capybara 2.7 the initial nil is required to indicate you aren't using the normal locator that would be passed to find_link (link text, etc), in Capybara 2.8 when released it won't be necessary. Note: the regex is matched against what node['href'] returns which in most drivers is the href property (as opposed to attribute) and is therefore normalized to be the full url the link refers to - http://example.com/abc/def even though the attribute in the document may just be set to /abc/def. If you are actually looking for more than one result then you can do

page.all(:link, nil, href: /regex to match against/)

If instead you are just checking that a certain number of matching links (3) exist it would be

expect(page).to have_link(nil, href: /regex to match/, count: 3)

Upvotes: 4

Justin Ko
Justin Ko

Reputation: 46836

You can use a CSS-selector to find all links that have an href attribute starting with a text:

review_links = page.all('a[href^="../items/"]')
p review_links.map(&:text)
#=> ["Some link title", "Some link title 2"]

Note that the href^= means an href attribute starting with.

Upvotes: 2

Related Questions