Capybara::Ambiguous match, found 2 elements matching xpath - Find 1st link

Viewed 2270

I'm having an index action where I list all blog posts

<% @posts.each do |post| %>
<div class="blog-post">
  <h2 class="blog-post-title"><%= link_to post.title, post_path(post) %></h2>
  <p><%= post.sort_description %></p>
  <p class="blog-post-meta">
     <%= link_to 'Read more', post_path(post) %>
  </p>
</div>
<% end %>

In my test script, in order to access the show action and view a single post I have this

find(:xpath, "//a[@href='/posts/1']").click
# or click_link(href: post_path(post)) 

But when I try to run the test I get this error

Failure/Error: find(:xpath, "//a[@href='/posts/1']").click

     Capybara::Ambiguous:
       Ambiguous match, found 2 elements matching xpath "//a[@href='/posts/1']"

as capybara finds two different links which go to same page (one on title and the "read more" link). Is there a way to tell capybara to use the first link that finds?

2 Answers
Related