This blog is part of our Rails 5.2 series.
Rails has inbuilt feature to preview the emails using Action Mailer previews.
A preview mailer can be setup as shown here.
class NotificationMailer < ApplicationMailer
def notify(email: email, body: body)
user = User.find_by(email: email)
mail(to: user.email, body: body)
end
end
class NotificationMailerPreview < ActionMailer::Preview
def notify
NotificationMailer.notify(email: User.first.email, body: "Hi there!")
end
end
This will work as expected. But our email template is displayed differently based on user's role. To test this, we need to update the notify method and then check the updated preview.
What if we could just pass the email in the preview URL.
http://localhost:3000/rails/mailers/notification/[email protected]
In Rails 5.2, we can pass the params directly in the URL and params will be available to the preview mailers.
Our code can be changed as follows to use the params.
class NotificationMailerPreview < ActionMailer::Preview
def notify
email = params[:email] || User.first.email
NotificationMailer.notify(email: email, body: "Hi there!")
end
end
This allows us to test our mailers with dynamic input as per requirements.

Written byPrathamesh Sonpatki
Related blogs
- 01Rails 5.2 DSL for configuring Content Security PolicyOctober 23, 2018 · Sushant Mittal
- 02Rails 5.2 stops some raw SQL, prevents SQL injectionsOctober 16, 2018 · Piyush Tiwari
- 03Rails 5.2 added method write_multi to cache storeJuly 3, 2018 · Rohan Pujari
- 04Rails 5.2 uses AES-256-GCM authenticated encryptionJune 26, 2018 · Sushant Mittal