longestdrive's avatar

Test Mail and number of emails send

Hi

My Laravel 5.5 testing journey continues

How do I test how many emails were sent by my test.

I'm trying to test that multiple emails were sent in a test. The method I'm testing against is only sending to the first recipient so I need to find a way of building a test

My current test is this:

    public function testUserCanSendBroadcastMessageToMultiplePlayers()
    {
    $this->disableExceptionHandling();

    Mail::fake();

    factory(Player::class, 4)->create();

    $players = Player::get()->pluck('id')->toArray();

    $request = [
        'recipients'=>$players,
        'subject'=>"test subject",
        'message'=>'test message'
    ];

    $response = $this->actingAs($this->user)
        ->call('POST', 'broadcast/create', $request);

    $subject = "test subject";
    $message = "test message";

    Mail::assertSent(NewBroadcastMessage::class, function ($mail) use ($subject, $message) {
        $mail->build();
        return $mail->subject === $subject;
    });
    
    }

I don't know where I should count() the emails sent. H

How do I build my test correctly?

0 likes
4 replies
longestdrive's avatar

@JONASSIEWERTSEN - That's great. Thank you.

Will give the api a good read, I often forget about that resource as it rarely comes up in the searches I do.

Thanks again

?

longestdrive's avatar

I've tried to implement the solution but come up with this error:

Error : Call to protected method Illuminate\Support\Testing\Fakes\MailFake::assertSentTimes() from context 'Illuminate\Support\Facades\Facade'

How can I call this method correctly?

I'm importing the class using:

use Illuminate\Support\Facades\Mail;

longestdrive's avatar

FOund the answer - again in the API! (Will I never learn)

You need to pass a numeric value to the AssertSent callback as a numeric which then calls the protected method AssertSentTimes

3 likes

Please or to participate in this conversation.