Capybara will not find links without an href attribute

Capybara will fail to find <a> tags that are missing an href attribute. This will probably happen to you every now and then on JavaScript-heavy applications.

An example would be an AngularJS application where the following HTML actually works. [1]

<a ng-click="hello()">Hello</a>

Capybara will fail to find that link, even though looking it up via the DOM shows it:

>> find_link("Hello")
Capybara::ElementNotFound: Unable to find link "Hello"

>> find("a").text
=> "Hello"

To make find_link and click_link work, simply add href="#" to your element:

    <a href="#" ng-click="hello()">Hello</a>
>> find_link("Hello")
=> #<Capybara::Element tag="a">

[1] Note that while it does work in your application (links are usually styled correctly, and Angular will take care of the click event), the HTML spec Show archive.org snapshot defines hyperlinks as anchor tags (<a>) that have an href attribute. Without an href they are just link placeholders. So Capybara at least adheres to the HTML spec Show archive.org snapshot . :)

Arne Hartherz Over 9 years ago