Search code examples
htmlrubyrspeccapybarainternal-link

How can I get verbatim href attribute


I have a page-internal link in an html page:

<div class="bar">
  <a href="#foo">Go to foo</a>
</div>

I selected this anchor element using Capybara matcher. When I try to access the href attribute, the value is expanded to full URL:

find(".bar a")[:href] # => "http://path/to/page#foo"

How can get only the internal link, i.e., the verbatim href value?

find(".bar a")... # => "#foo"

Solution

  • Capybara returns the property href (as opposed to the attribute) in JS capable drivers, which is normalized. To get access to the attribute value you will need to use evaluate_script

    link = find(".bar a")
    evaluate_script("arguments[0].getAttribute('href')", link)
    

    If, on the other hand, you just want to verify the link has that specific href attribute you can do that with the :link selector

    expect(page).to have_link('Go to foo', href: '#foo')
    

    or to find the link by the href attribute

    link = find(:link, href: '#foo')
    

    etc...