This article was posted over one year ago, the information may no longer be acurate.
Click on an image in a link with Capybara
There is the built-in click_link method when you want to follow a link in your Capybara tests:
This works fine when you are testing a text link; however, this doesn't work when there is no text. Like a link with an image for example:
<a href="/post/3/edit"> <img alt="Edit" src="/images/edit.png" /> </a>
Luckily there are some simple workarounds, here are two.
The id attribute
You can simply add an id attribute to the link you want to follow. The click_link method will see this link and, voilà, problem solved. The test stays clean but you'll need to add some view logic to make sure you are using a unique id for each link.
The Capybara XPath finder
We could turn this upside down by changing the test instead of the view. This means we'll need to find a way to get the right element from the DOM with Capybara:
There is one caveat here. The /.. at the end selects the parent element from the XPath result (the link and not the image in our case). If you leave this out Capybara will click on the image and for some reason that doesn't seem to work.