Search code examples
ruby-on-railsrubycapybaracapybara-webkit

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?


Solution

  • 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.