Using ActionMailer::Preview with Devise mailers in Rails 4.1

ActionMailer::Preview is pretty awesome and newly introduced in Rails 4.1+

It allows you to preview formatting of emails from within the browser without having to send emails just to be able to preview them in the email client.

This substantially reduces the duration of each development cycle between coding and testing a modification.

If you want to use ActionMailer::Preview with Devise, I assume you have already installed the Devise gem and have configured it properly and authentication is working.

Be sure to also generated the devise views so you can customize the mailer.
To generate the devise views, do the following:

rails generate devise:views

Under your app/views directory, you should now see ‘devise’ and ‘devise/mailer’. You’ll probably see different list of devise mailer views depending on which devise modules you’ve activated.

I see 3 mailers:

  • confirmation_instructions.html.erb
  • reset_password_instructions.html.erb
  • unlock_instructions.html.erb

Create a preview class for Devise

By default preview classes will reside under test/mailers/previews

Do the following under your project directory

mkdir -p test/mailers/previews/devise

Under the test/mailers/preview/devise directory, create a file called mailer_preview.rb and paste the following in there:

class Devise::MailerPreview < ActionMailer::Preview
  # hit http://localhost:3000/rails/mailers/devise/mailer/confirmation_instructions
  def confirmation_instructions
    Devise::Mailer.confirmation_instructions(User.first, {})

  # hit http://localhost:3000/rails/mailers/devise/mailer/reset_password_instructions
  def reset_password_instructions
    Devise::Mailer.reset_password_instructions(User.first, {})

  # hit http://localhost:3000/rails/mailers/devise/mailer/unlock_instructions
  def unlock_instructions
    Devise::Mailer.unlock_instructions(User.first, {})

You should now be able to preview the following emails in the browser:

These sites have been very useful for me. Please see: ActionMailer::Preview and Styling emails with Rails and Roadie

VN:F [1.9.22_1171]
Rating: 5.0/5 (6 votes cast)
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)
Using ActionMailer::Preview with Devise mailers in Rails 4.1, 5.0 out of 5 based on 6 ratings
Facebook Twitter Email

Leave a Reply