Cut PHP Code Review Time & Bugs into Half with CodeRabbit

Testing Mailable Content in Laravel 8

Published on by

Testing Mailable Content in Laravel 8 image

Never Miss a Laravel Release 🚀

Sign up and get an email with each new Laravel release

Laravel 8.18.0 added methods to test HTML and plain-text email bodies for mailables. These methods are documented, but I’d like to walk through a simple example to illustrate how useful these can be.

The documentation demonstrates the following methods you can use to test mailables:

public function test_mailable_content()
{
$user = User::factory()->create();
 
$mailable = new InvoicePaid($user);
 
$mailable->assertSeeInHtml($user->email);
$mailable->assertSeeInHtml('Invoice Paid');
 
$mailable->assertSeeInText($user->email);
$mailable->assertSeeInText('Invoice Paid');
}

As you can see, the mailable instances conveniently provide assertion methods you can use to ensure emails contain expected content. Let’s walk through a simple example that can help solidify this concept.

Getting Started

Let’s say you are building a simple email that sends a confirmation code to the user’s email to verify something before they are allowed to act. We will send an HTML version, but you can test plain-text versions of your email and refer to the above examples for the text assertions.

Let’s start with a new Laravel project using Laravel’s documented installation method for Laravel Sail:

# I use ~/code/sandbox as path for playground projects
cd ~/code/sandbox
curl -s https://laravel.build/mailable-demo | bash

Once you have the project created, you can start the Laravel app server:

vendor/bin/sail up -d

Creating the Mailable

We are ready to create the mailable we’ll be testing, along with the accompanying template. We’ll use the artisan console to create the class and create the template in our project:

# Create the mailable
sail artisan make:mail ConfirmationCode
 
# Create the template
mkdir -p resources/views/emails
echo 'Hello from HTML!' \
> resources/views/emails/confirmation-code.blade.php

Next, update the ConfirmationCode class to look as follows:

<?php
 
namespace App\Mail;
 
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
 
class ConfirmationCode extends Mailable
{
use Queueable, SerializesModels;
 
/**
* @var string
*/
public $code;
 
/**
* @var \App\Models\User
*/
public $user;
 
/**
* Create a new message instance.
*
* @param string $code
*/
public function __construct(User $user, string $code)
{
$this->user = $user;
$this->code = $code;
}
 
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.confirmation-code');
}
}

We will use a simple string $code property for the mailable, but perhaps a real implementation might use a service responsible for generating random codes tied to a user.

Next, let’s use the provided tests/Feature/ExampleTest.php file to test our mailable:

<?php
 
namespace Tests\Feature;
 
use App\Mail\ConfirmationCode;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
 
class ExampleTest extends TestCase
{
use RefreshDatabase;
 
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$user = User::factory()->create();
$subject = new ConfirmationCode($user, '1234');
 
$subject->assertSeeInHtml('Hello from HTML!');
}
}

At this point your test should pass:

vendor/bin/sail test tests/Feature
 
PASS Tests\Feature\ExampleTest
basic test
 
Tests: 1 passed
Time: 1.06s

Next, let’s adjust the test to expect the confirmation code:

public function testBasicTest()
{
$user = User::factory()->create();
$subject = new ConfirmationCode($user, '1234');
 
$subject->assertSeeInHtml('Hello ' . $user->name);
$subject->assertSeeInHtml('Here is your confirmation code: <strong>1234</strong>');
}

The test will fail now if you rerun it. Next, let’s update the template to include the user’s name and include the confirmation code:

{{-- resources/emails/confirmation-code.blade.php --}}
Hello {{ $user->name }}
 
Here is your confirmation code: <strong>{{ $code }}</strong>

At this point, your test will pass, and you can ensure that your mailable includes the necessary confirmation code!

In a real application, you’d likely generate the email code from a service and swap it out with a fake or a partial mock, but you can see how we can ensure the mailable template has the expected text. It is convenient that you can now test your mailables without additional work or packages directly! Be sure to check out the official Laravel Mail documentation to learn more about mailables.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026 image

Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026

Read article
Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development image

Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development

Read article
JSON:API Resource in Laravel 12.45 image

JSON:API Resource in Laravel 12.45

Read article
Caching With MongoDB for Faster Laravel Apps image

Caching With MongoDB for Faster Laravel Apps

Read article
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article
Handle Nested Data Structures in PHP with the Data Block Package image

Handle Nested Data Structures in PHP with the Data Block Package

Read article