Rails 5.2 pass request params to Action Mailer previews

Prathamesh Sonpatki

Prathamesh Sonpatki

January 8, 2018

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.

1class NotificationMailer < ApplicationMailer
2def notify(email: email, body: body)
3user = User.find_by(email: email)
4mail(to: user.email, body: body)
5end
6end
7
8class NotificationMailerPreview < ActionMailer::Preview
9def notify
10NotificationMailer.notify(email: User.first.email, body: "Hi there!")
11end
12end

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.

1http://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.

1class NotificationMailerPreview < ActionMailer::Preview
2def notify
3email = params[:email] || User.first.email
4NotificationMailer.notify(email: email, body: "Hi there!")
5end
6end

This allows us to test our mailers with dynamic input as per requirements.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.