How do I preview emails in Rails?
This might be a dumb question but when I'm putting together an HTML email in Rails, is there a particularly easy built-in way to preview the template it in the browser or do I need to write some sort of custom controller that pulls it in as its view?
Solution 1:
Action Mailer now has a built in way of previewing emails in Rails 4.1. For example, check this out:
# located in test/mailers/previews/notifier_mailer_preview.rb
class NotifierPreview < ActionMailer::Preview
# Accessible from http://localhost:3000/rails/mailers/notifier/welcome
def welcome
Notifier.welcome(User.first)
end
end
Solution 2:
Daniel's answer is a good start, but if your email templates contain any dynamic data, it won't work. E.g. suppose your email is an order receipt and within it you print out @order.total_price
- using the previous method the @order
variable will be nil.
Here's a little recipe I use:
First, since this email preview functionality is definitely for internal use only, I set up some generic routes in the admin namespace:
#routes.rb
MySite::Application.routes.draw do
namespace :admin do
match 'mailer(/:action(/:id(.:format)))' => 'mailer#:action'
end
end
Next, I create the controller. In this controller, I create one method per email template. Since most emails contain dynamic data, we need to populate whatever member variables the template expects.
This could be done with fixtures, but I typically prefer to just grab some pseudo-random real data. Remember - this is NOT a unit test - this is purely a development aid. It doesn't need to produce the same result every single time - in fact - it's probably better if it doesn't!
#app/controllers/admin/mailer_controller.rb
class Admin::MailerController < Admin::ApplicationController
def preview_welcome()
@user = User.last
render :file => 'mailer/welcome.html.erb', :layout => 'mailer'
end
end
Note that when we render the template, we use layout=>:mailer
. This embeds the body of your email inside the HTML email layout that you've created instead of inside your typical web application layout (e.g. application.html.erb
).
And that's pretty much it. Now I can visit http://example.com/admin/mailer/preview_welcome to preview change to my welcome email template.
Solution 3:
37Signals also has their own mail testing gem called mail_view. It's pretty fantastic.