How to click links in Rails Mailers when writing tests
In this tutorial, you’ll learn how to write a test that clicks a link in a Rails mailer. This is particularly useful when testing emails with links that require unique tokens or may expire, such as password reset emails. We’ll cover the steps to create a helper method that uses Capybara to find and click the link in the email, allowing you to fully test the functionality of a passpword reset email.
Find the link using Nokogiri
To extract links from emails, we can use Nokogiri. Nokogiri converts the body of the email into a document object, which we can navigate to extract links based on their text.
Replace Nokogiri with Capybara
One way to improve the current implementation is by swapping out Nokogiri for Capybara. This would enhance the readability of the test and allow us to utilize Capybara’s DSL to locate more email content.
Create a test helper to return the link
The Capybara implementation is helpful, but it could be made simpler. We can create a method that takes an email and a string, and uses Capybara to find and return the link with that text. This method could be extracted into a helper to hide the implementation details.
Since it’s best practice for mailers to use absolute URLs, we can take this opportunity to convert them to relative URLs. The reason for this is to avoid making requests to “example.com” which is the default test host for Rails action mailer. This isn’t an issue for integration tests, but it can cause problems for system tests because Capybara may try to visit the external URL instead of staying on the localhost.
Create a test helper to set the current email
To make our test easier to read, we can create another helper. This helper will
find the most recent email sent to a specific email address and set it as the
current_email
. Without this helper, the current_email
will just default to
the last email sent, regardless of the recipient.