This post originally appeared on the (now retired) Versa Engineering blog

rspec tdd meme

Update: very similar email preview functionality has been integrated into Rails 4.1

Here in the Versa Nerdery, we send HTML emails. We also build our mailers via Test Driven Development (TDD).

One way we’ve tried to limit the effects of context switching between building email logic and implementing the email design (we are full stack engineers, so we do both) is to use our tests to build easily accessible previews of our HTML emails.

Here is a piece of code we have in our spec_helper.rb file:

# Helper method for generating HTML emails to test.
# @email_name - Name for the email. This is what the html file will be named.
# By convention, we use the mailer action that creates the email.
#
# @message_html - a string of html, usually the result of calling '.body' on an ActionMailer object.

def generate_html_email(email_name, message_html)
  email_path = File.join(Rails.root,"public","emails","#{email_name}.html")
  IO.write(email_path, message_html)
  puts "Preview email at: #{root_url}emails/#{email_name}.html"
end

Then, in our mailer test we call this method just before we leave the test, passing in the name of the mailer action we are testing and the message body generated by the test.

# Contrived example of a UserMailer that sends the user
# a "Welcome to the Versa platform!" email

describe UserMailer do
  describe 'welcome_to_platform' do
    before :each do
      user = FactoryGirl.create :user, :email => 'john@fakecorp.com'
      @message = UserMailer.welcome_to_platform(user)
    end

    it 'should set the reciever email' do
      @message.to.should eq ['john@fakecorp.com']
      generate_html_email('welcome_to_platform', @message.body.encoded)
    end

    ...real tests...
  end
end

Helpful blog post: How to test mailers in Rails 3 / 4 with Rspec

When this spec runs, it will generate an HTML file in the public/emails/ folder. This means that to preview the email you just need to point your browser to http://your_app.url/emails/welcome_to_the_platform.html and see the email in all its HTML goodness!

As you implement the email’s design you can get an updated preview by just running your spec. If you’ve got automated specs (using something like guard), you don’t need to do anything; the specs will build your preview automatically - just hit refresh.

This simple solution is not perfect for all cases, but it has sped up our development process by providing a flow for building HTML emails that mimics our flow for building HTML pagIf you want to preview emails in your development environment when they are sent, you can use Ryan Bates’ Letter Openner - it seems better for testing emailing as part of a larger flow of an app. There is also the fake SMTP server, Mailtrap, but again, it seems less suited to preview emails while implementing design.