Testing to Ensure Not Sending Mail

April 12, 2022   • ruby testing

Today at work, I was trying to add tests for an email notification feature I wrote last week. Without going into too much detail, the way it works is that the app should only send the email under certain circumstances. So I wanted to write a test to ensure that the app was not sending an email under those conditions.

Here is the recommended answer on StackOverflow.

expect { mail }.not_to change(ActionMailer::Base.deliveries, :count)

It didn’t work for me, as the method I was testing didn’t deliver the email but returned an instance of ActionMailer::MessageDelivery. Some other method took care of calling deliver_later on it.

Luckily, MessageDelivery has a message method that returns the resulting Mail::Message. When the mail is not sent, Rails sets this to an instance of ActionMailer::Base::NullMail.

So this is how I implemented the test instead.

expect(mail.message).to be_an_instance_of(ActionMailer::Base::NullMail)

What do you think?