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

  • Importance of backups

    Well… here we are.  10 years later, and … no backups.  Or… none of the data that’s important. Recently had a drive crash in my main server where this blog is hosted.  Had it happen 2 years ago, but the data was recovered, and I put everything on automatic backups.  Using virtualmin, a great control…

  • Bad I9 PDF form

    Have been needing to programmatically fill out an I9 PDF, retrieved from gov site. Should be fairly straightforward, right? Well… the field names are… a mess. Field names like topmostSubform[0].Page1[0].U\.S\._Social_Security_Number__Last_4_numbers_[0]topmostSubform[0].Page1[0].expiration_date__if_applicable__mm_dd_yyyy[0] topmostSubform[0].Page2[0].Employers_Business_or_Organization_Address_Street_Number_and_Name[0] and so on make it pretty… not straightforward to create a usable key/value combination to search and replace. But… today, I noticed it got…

Leave a Reply

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