Go to foo I selected this anchor element using Capybara match" /> Go to foo I selected this anchor element using Capybara match" /> Go to foo I selected this anchor element using Capybara match"/>

How can I get verbatim href attribute

162 Views Asked by At

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"
1

There are 1 best solutions below

0
Thomas Walpole On BEST ANSWER

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