Testing Laravel mailable content

This has been a thorny issue for a while, and *may* have been resolved in Laravel 9 (have not upgraded projects to 9 yet). Testing both that an email was triggered in a Laravel test, as well as verifying the content of the mail body – that has often seemed to be a tricky step. If it’s resolved in modern times… great. If not (or you’re dealing with legacy code to test), read on.

public function testCustomerOrderedItems()
{

    $customer = Customer::factory()->create();
    $item = Item::factory()->create();
    $service = $this->app->make(OrderService::class);
    $service->order($item, $customer);

    Mail::assertSent(ItemOrdered::class, function ($mail) use ($customer, $item) {
        $mail->build();
        $markdown = $this->app->make(Markdown::class);
        $body = $markdown->renderText($mail->view, $mail->buildViewData())->toHtml();
        $this->assertStringContainsString('Ordered', $body);
        $this->assertStringContainsString($item->number, $body);

        return $mail->hasTo($customer->email);
    });

} 

Of course, I can’t specifically remember where I discovered this series of steps, so apologies to whomever I may have copied this from.

A couple of things to keep in mind…

1. This only works with Markdown mailable. I’ve not used anything else during testing, so… if you’re using something else, you’re on your own here.
2. The $mail->view – this is a public property I needed to add to mailables (like ItemOrdered mailable) to be able to reference in the tests. It’s the name of the markdown/blade file – item.ordered.blade, for example.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *