Bom_Basti's avatar

[SOLVED but not SOLVED] Test the subject and from-address

Hi,

I want to test the "to", "from" and "subject" of an Mailable in Laravel 5.5.

If I write my test like this, everything is working fine, if the "to" address matches.

Mail::assertSent(NewOffer::class, function ($mail) {
        return $mail->hasTo('[email protected]');
});

But if I want to test the "from" and "subject" of this mail, I get null and this test is failing. A dd on $mail->subject and $mail->from or $mail->hasFrom('[email protected]') shows null.

If I go to the site, do what it needs to do to send this mail, everything is fine. The subject and from address matches my configuration.

What do I need to do to test the subject and from address in my test?

Thanks for your help!

0 likes
4 replies
ejdelmonico's avatar

Are you creating the mail with Mail::fake()? You could assert against know data by altering your mail fake assertions

Mail::fake();

Mail::assertSent(NewOffer::class, function ($mail) use ($user) {
            return $mail->hasTo($user->email) &&
                   $mail->hasSubject('your-subject') &&
                   $mail->hasFrom('your-from');
        });

I am not positive it will work but worth a try.

Bom_Basti's avatar

Thank you @ejdelmonico for your reply.

I've set up the Mail::fake() call in my setUp() method in this test class. But even if I call it in my test method directly my mail is "empty".

If I dump the $mail variable inside the callback, everything is null, except the to field.

Mail::fake();

// Perform post request

Mail::assertSent(NewOffer::class, function($mail) {
    dd($mail);
});

This is the dump:

+from: []
  +to: array:1 [
    0 => array:2 [
      "name" => null
      "address" => "[email protected]"
    ]
  ]
  +cc: []
  +bcc: []
  +replyTo: []
  +subject: null
  #markdown: null
  +view: null
  +textView: null
  +viewData: []
  +attachments: []
  +rawAttachments: []
  +callbacks: []
  +connection: null
  +queue: null
  +delay: null
  +chained: []

But if I remove the callback, the test passes. And the mail that is sent has an subject and so on.

Bom_Basti's avatar
Bom_Basti
OP
Best Answer
Level 15

I've got a temporarily solution after seeing a similar issue at github.

If I call the $mail->build() method inside the callback, all fields in the $mail variable are filled.

But I don't know why.

Mail::assertSent(NewOffer::class, function ($mail) {
    $mail->build();

    return $mail->hasTo('[email protected]')
        && $mail->hasFrom('[email protected]');
});

And this passed.

9 likes
atorscho's avatar

Thank you for your solution!

This is something that should either be written in the docs or (better) made behind the scenes.

Please or to participate in this conversation.