Skip to content
Advertisement

Laravel unit testing emails

My system sends a couple of important emails. What is the best way to unit test that?

I see you can put it in pretend mode and it goes in the log. Is there something to check that?

Advertisement

Answer

There are two options.

Option 1 – Mock the mail facade to test the mail is being sent. Something like this would work:

$mock = Mockery::mock('Swift_Mailer');
$this->app['mailer']->setSwiftMailer($mock);
$mock->shouldReceive('send')->once()
    ->andReturnUsing(function($msg) {
        $this->assertEquals('My subject', $msg->getSubject());
        $this->assertEquals('foo@bar.com', $msg->getTo());
        $this->assertContains('Some string', $msg->getBody());
    });

Option 2 is much easier – it is to test the actual SMTP using MailCatcher.me. Basically you can send SMTP emails, and ‘test’ the email that is actually sent. Laracasts has a great lesson on how to use it as part of your Laravel testing here.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement