Testing Ruby on Rails email sends for specific User or Plan types in the Console

Submitted over 3 years Ago

Share This Post

Sending emails can be tricky. You can’t see the result of your work until it is sent. The Letter Opener gem is really handy to use in dev, because you can test email sends without a lot of set up. However, if you need to test something specific to a user or plan type, using Letter Opener won’t work. The bottom line is that if you are sending user emails you want to make sure that they are absolutely right before they are deployed to production. But how to do this?

Using your console is a great tool for this. However, it works in some different ways than you might think. When I started with Ruby on Rails, the shortcut explanation for the console was “it just loads your Rails app right there”. Well, that is only part of the story. You actually need to interact with the console a bit differently.

Here is a specific example to make the point:

The other day I was updating a welcome email. The change was to only show a specific section of the email body for users that have a specific subscription plan. If they don’t have that subscription plan, they just don’t see that part of the content. This was a one line code change because I was just adding an “if” to the already existing content, to only show it for these specific plan types. While I know it may be tempting to just wing that in and test on production, testing the change in dev is actually really easy in the console once you understand how it works.

The important point is that while the console does load your Rails app, it does not have a knowledge of instance characters. So you need to tell it the class name, and you actually need to tell it which user to find for that email test send.

Let’s get started:

Navigate to the Rails console:

$ rails c

Then run your command by naming the class you want (make sure you capitalize it) and find the specific user you want. In this case, the second user in my local database had the plan type I was testing. Here my file is called “welcome_message_email.html.haml”. Note that you are only using the file name, not including the file type.

Then run this:

> UserMailer.welcome_message_email(User.second).deliver_now

(Why is it not @user? Remember the comment above, the console cannot reference an instance variable.)

This will open the email in a browser tab on your computer and will appear exactly as if it had been sent to that user. It will show you the email title and the content body, formatting in html just as the user will see it.

So that is how to test email content for specific plan types for specific users right in your development environment, from the console. Easy peasey!

Share This Post

Like this post? Star it on GitHub

Star It

See All Blog Posts