Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel assert multiple recipients of email during PHPUnit test

I want to test that an email has been sent to a number of addresses during a PHPUnit test. How can I achieve this?

like image 877
RonnyKnoxville Avatar asked Dec 09 '25 09:12

RonnyKnoxville


1 Answers

Although the Laravel documentation does indicate that a hasTo() function exists within the Mail object:

// Assert a message was sent to the given users...
Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
    return $mail->hasTo($user->email) &&
                   $mail->hasCc('...') &&
                   $mail->hasBcc('...');
});

It does not make clear that it is possible to assert that multiple address have been sent the mail. The hasTo function accepts the following structure as expected assertions:

[
    [
        'email' => '[email protected]',
        'name' => 'Johnny Appleseed'
    ],
    [
        'email' => '[email protected]',
        'name' => 'Jane Appleseed'
    ],
]

As the name key is optional, the simplest way to test that specific users have received an email would look something like this:

Mail::fake();

$admins = User::where('administrator', true)->get()->map(function ($admin) {
    return ['email' => $admin->email];
})->toArray();

Mail::assertSent(MyMailable::class, function ($mail) use ($admins) {
    return $mail->hasTo($admins);
});

If you have used the default Laravel User model, or your user model has both name and email properties, you can pass your users in as a collection

Mail::fake();

$admins = User::where('administrator', true)->get();

Mail::assertSent(MyMailable::class, function ($mail) use ($admins) {
    return $mail->hasTo($admins);
});
like image 115
RonnyKnoxville Avatar answered Dec 10 '25 23:12

RonnyKnoxville



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!