Learn about testing mailers functionalities and how to write the test for emails and make them pass.
We'll cover the following
Testing mailers functionalities
Testing Rails mailers involves the following two separate bits of functionality:
- To specify whether the email gets sent as a result of some action.
- To specify that email’s contents. Specifying whether the email gets sent often starts as part of a request or system test while specifying the content has a lot in common with view testing. The somewhat indirect nature of the Rails ActionMailer makes testing email less obvious than it might be, but it’s not hard. We’ll also look at a third-party library that makes email testing easier.
For example, we want to send an email in the project-management system when a task is marked as complete. We don’t have a user model yet (we’ll talk about users in this system when we get to the chapter “Testing for Security”), so let’s assume for the moment that all the emails go to some common audit or monitoring address.
At this point, we have one of those weird, unique-to-book-examples problems. Specifically, we haven’t written much of the task-tracker site, just a project index and a new-project page. We don’t have a list of tasks on a single project, let alone a way to mark a task as complete.
Writing the test
Let’s wildly hand-wave our way out of that, writing a request test for just the mail being sent when a task is complete. This will probably imply the existence of pages or functionality we haven’t written yet, but for now, let’s all pretend it’s already there.
With that hand-waving out of the way, let’s write the test, starting with thinking about what we need:
- Given: We need one task that starts incomplete.
- When: The action of this test is a controller action. In a RESTful Rails interface, that action would be
TasksController#update. Let’s go with that. The controller action has a
- Then: The task updates and an email is sent.
A simple case to start with, where
completed is not set, and no email is sent. Writing that test first will let us write the structure of the method.
Note: When testing a Boolean condition, make sure to write a test for both halves of the condition.
These tests cover the “send email” and “don’t send email” cases: