capybara: click_link 'foo' not working on links without href

Running click_link ‘Title View’ against

<a id="title-view-link">Title View</a> 

results in Capybara::ElementNotFound: no link with title, id or text ‘Title View’ found . Adding an empty href -

 <a id="title-view-link" href="">Title View</a> 

works.

So, is the code testing for links by looking for a elements with href attributes? If so, shouldn’t it drop the href attribute as mandatory?

About this issue

  • Original URL
  • State: closed
  • Created 13 years ago
  • Reactions: 3
  • Comments: 20 (6 by maintainers)

Most upvoted comments

find("a", :text => "whatever").click 👍

Thank you

@michaelrkn standard is kind of a binary concept, it either is standard or it isn’t. In this case, standard means the HTML5 spec. This is the relevant section:

If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element’s contents.

I don’t think this can be much clearer. “then it represents a hyperlink”. otherwise is does not.

Capybara will happily click on anything you can throw at it, by the way, it just won’t find it as a link, if you do click_link. find("a", :text => "whatever").click will work just fine, href or not.

Adding href="#" is the right concept, but is actually bad practice for the general case: http://www.javascripttoolbox.com/bestpractices/#onclick

Unless you intend to use the effect of href="#", which is to force the user to jump back to the top of the page if they are below the fold, it should always be avoided. Also when used in conjunction with the <base> tag, these href="#" links will navigate away from the current page to the base URL.

The ‘best-practice’ syntax is:

    <a href="javascript_required.html?doSomething" onclick="doSomething(); return false;">go</a>

I have never tried this, but I think you might be able to do find(:css, '#foo').click.