The Rails guides have a section about how to preview emails in your app so that you can work on them in development without the need to actually send the emails out. The process is straight forward, I’ll take you another example just in case you don’t want to open the other link :)
Let’s assume you’re building a simple app that asks users to sign up and once they have, you send them a welcome email. Nothing fancy. If you want to test out your email, you would create a file under the test directory, more precisely under the test/mailers/previews/sign_up_mailer_preview.rb:
# Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer
class SignUpMailerPreview < ActionMailer::Preview
def welcome_email
SignUpMailer.welcome_email User.first
end
end
But as you can tell, this scenario assumes that you already have a user in the database, which it fetches and then uses in the email. You obviously need a user in order to mimic exactly the process of the app. But… you might not want to use data from the DB, for many reasons, one being that you might want to control exactly what data you are fetching, the first user in your DB might not represent exactly what a newly registered user looks like.
The other option you can opt for is using fixtures. Or in our case, using FactoryGirl:
# Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer
class SignUpMailerPreview < ActionMailer::Preview
def welcome_email
user = FactoryGirl.create(:user)
SignUpMailer.welcome_email user
end
end
But now we have another problem that arises, each time you try to preview the welcome email, you are creating a new user in the DB. Not only does that pollute your dev DB with unnecessary rows, it is also susceptible to validations errors, like a uniqueness validation on the email. The easy fix is to use FactoryGirl.build instead of FactoryGirl.create which does not save the user to the DB and avoids adding the rows and the validation errors. With a tiny caveat, if you are including an URL in the email that links to a path dependent on the user, like profile_path(user), you would need an object that was persisted to the DB, mostly because the `to_params` in this case is returning an ID, which is then passed to the path helper, and if the object is not persisted it would not have an ID.
Which brings us to the next iteration:
# Preview all emails at http://localhost:3000/rails/mailers/sign_up_mailer
class SignUpMailerPreview < ActionMailer::Preview
def welcome_email
mail = nil
ActiveRecord::Base.transaction do
user = FactoryGirl.create(:user)
mail = SignUpMailer.welcome_email user
raise ActiveRecord::Rollback, “Don’t really want these objects committed to the db!”
end
mail
end
end
ActionMailer::Preview expects a Mail object to be returned, which is why we need to return it at the end of the method. In between, we utilize the transaction feature of ActiveRecord to create the elements and then rollback all the changes after we’re done using them in the mailer.
Unfortunately, we’re not done yet! This setup can get very complicated, and resource intensive. Consider the scenario where you want to send an email after a Comment has been posted. This Comment object depends on a Post object, which depends in turn on an Author object. Maybe you can also imagine the Post being dependent on a Publication, and so on and so forth. That’s a lot of set up that needs to go into the mailer preview. If you’ve done it right, you have all of those associations included in your FactoryGirl definitions. It is still a lot of DB objects that are being created.
Every once in a while, you get the following error: ActiveRecord::AssociationTypeMismatch with something like Expected User(12345678) got User(12345679) and the only difference is the ID of the object. That stumped me for a while. It expected a User and got a User. WAT?
From what I’ve read, Rails renders the preview in two parts. The top part that represents the headers of the email, and the bottom part which is the body of the email. So my very unscientific conclusion is that some of the objects are getting redeclared, maybe because they are getting garbage collected? If anyone has a better understanding of this issue, I definitely would appreciate a clarification.
To get around that problem, I’ve come up with this solution:
# Preview all emails at http://localhost:3000/rails/mailers/comments_mailer
class CommentsMailerPreview < ActionMailer::Preview
def notify_author
author = OpenStruct.new(FactoryGirl.attributes_for(:author))
reader = OpenStruct.new(FactoryGirl.attributes_for(:reader))
article = OpenStruct.new(FactoryGirl.attributes_for(:article).merge({ author: author }))
comment = OpenStruct.new(FactoryGirl.attributes_for(:comment).merge({ article: article, reader: reader }))
CommentsMailer.notify_author comment
end
end
In this example, we are still using FactoryGirl to get the right attributes (eg. name, email, etc), with the knowledge that attributes_for does not return any associations. What I realized, though, is that the mailer couldn’t care less whether the objects it has are ActiveRecord objects or plain ole Ruby objects. At least in most instances. So, to get away from everything Rails related, OpenStruct is the perfect substitute as it provides the same interface and can be instantiated from the hash returned by FactoryGirl.attributes_for. The benefit we get from this approach is reducing the dependency on the DB and other elements that are not necessary for the task at hand.
We’ve covered different ways we can achieve the same outcome. Each of those has its pros and cons. Personally, I use the approach that creates AR objects when it’s feasible because that will mimic the real scenario more accurately, but when that fails or becomes too taxing on the app that it crashes the server locally, I resort to the OpenStruct approach. What strategies do you use for testing emails in development?