Ad

Laravel Assert Multiple Recipients Of Email During PHPUnit Test

- 1 answer

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

Ad

Answer

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);
});
Ad
source: stackoverflow.com
Ad