1

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"
sawa
  • 165,429
  • 45
  • 277
  • 381
  • Can't replicate this with capybara 2.4.3 and rspec 3.5.0. `find('.bar a')[:href] #=> "#foo"` – omnikron May 10 '17 at 09:50
  • @omnikron That is sort of surprising. I am using capybara 2.12.0 and rspec 3.5.0. – sawa May 10 '17 at 10:04
  • I don't suppose you're using any kind of path helper to generate the anchor tag...? Worth double-checking the html in that case maybe. Otherwise I am stumped. – omnikron May 10 '17 at 10:08
  • What driver are you using? – Thomas Walpole May 10 '17 at 15:01
  • @omnikron 2.4.3 is massively out of date – Thomas Walpole May 10 '17 at 16:23
  • Thanks for the heads up @ThomasWalpole. Is an upgrade going to be easy and make my tests faster? – omnikron May 10 '17 at 16:52
  • 1
    @omnikron 2.4.3 is over 2 years old, so while theoretically it should be an easy upgrade (semver, etc) a lot has been added. Not sure it will make your tests faster but it will make some types of expectations/behaviors cleaner to write and fixes a bunch of issues/differences between drivers, etc. – Thomas Walpole May 10 '17 at 16:55

1 Answers1

2

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

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78