Click on an image in a link with Capybara
Using Capybara’s ‘click_link’ to open a link or button without text.
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:
Luckily there are some simple workarounds Here are two.
The id attribute
You can 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 /.., in 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.