Heelcats113
Heelcats113

Reputation: 11

How to visit link in email opened with letter_opener gem

I am working on some QA automation using Cucumber and Capybara and have a step:

When(/^I follow the reset password link in the email$/) do
  last_email = ActionMailer::Base.deliveries.last
  password_reset_url = last_email.body.match(/http.*\/users\/password\/edit.*$/)
  visit password_reset_url
end

The step fails with:

undefined method `body' for nil:NilClass (NoMethodError)

Additionally, dropping binding.pry after the first line results in nil for last_email which is weird.

Does anyone have advice or thoughts on why that may be happening here?

Upvotes: 1

Views: 289

Answers (2)

Paul Fioravanti
Paul Fioravanti

Reputation: 16793

Tom Walpole's answer is absolutely correct in content and pointing you in the direction of the capybara-email gem.

Here's a potential example of how you could change your code sample, assuming that you have another Cucumber step that has clicked a button/link to send reset password instructions:

When(/^I follow the reset password link in the email (.*)$/) do |email|
  # finds the last email sent to the passed in email address.
  # This also sets the `current_email` object, which you can think
  # of as similar to Capybara's `page` object, but for an email.
  open_email(email)
  # Assuming the email link to change your password is called
  # 'Change my password', you can just click it, just as you would
  # on a Capybara `page`.
  current_email.click_link 'Change my password'
end

After clicking the link, you will be taken to whatever page where you can continue on to fill_in 'New password', with: 'foobar' etc, which I'm assuming you've got covered in another Cucumber step.

Upvotes: 0

Thomas Walpole
Thomas Walpole

Reputation: 49880

If you're using letter_opener then emails aren't going to ActionMailer deliveries and are being opened in a browser not controlled by Capybara. If you want to work with emails in capybara you should probably be looking at the capybara-email gem rather than letter_opener. Letter_opener is aimed more at the dev environment rather than test

Upvotes: 3

Related Questions