Lee Willis

Testing Laravel emails with MailThief

| 0 comments

The last couple of Laravel projects I’ve worked on have all included important emails being delivered. It was important that the triggering of these emails could be tested. I also needed to make sure that the correct email was being sent, as some processes would trigger different emails based on the data input.

In the first project, I relied on Mockery to test that Mail functions were called, e.g.

Mail::shouldReceive('send')
  ->once()
  ->with(
    'emails.enquiry',
    Mockery::any(),
    Mockery::any()
  );

This allowed testing that the correct email was being triggered. However if you want to test in more detail that that, for example testing that data from input has been inserted correctly into the email content then it gets a lot less straightforward. On the next project I tried to evolve how I was testing emails. I needed to do some more detailed testing on email contents, so I turned to the MailThief package.

This allowed me to easily test not only that emails were being triggered, but specific tests against the email content. Here’s some examples from my tests:

$this->seeMessageFor($company->email);
 $message = $this->lastMessage();
 $this->assertTrue(
  $message->contains('Web enquiry</title>'),
  $message->getBody('html')
 );
 $this->assertTrue(
  $message->contains('0100 000000'),
  $message->getBody('html')
 );
 $this->assertTrue(
  $message->contains('<a href="tel:0100000000'),
  $message->getBody('html')
 );

I find it much more consistent to keep assertions after the actions in my test rather than having them as expectations before my actions. The package has proved so flexible that I’ll be using it for all email-related tests in future.

Thanks Tighten Co!

  1. Stuff I’ve used
  2. Error tracking with Sentry
  3. Autotrack for Google Analytics
  4. WordPress performance tracking with Time-stack
  5. Enforce user password strength
  6. WYSIWYG with Summernote
  7. Backing up your Laravel app
  8. Adding Google Maps to your Laravel application
  9. Activity logging in Laravel
  10. Image handling in PHP with Intervention Image
  11. Testing Laravel emails with MailThief
  12. Assessing software health
  13. IP Geolocation with MaxMind’s GeoLite2
  14. Uptime monitoring with Uptime Robot
  15. Product tours with Hopscotch
  16. Background processing for WordPress
  17. Using oEmbed resources in Laravel

Leave a Reply

Required fields are marked *.