laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.52k stars 11.02k forks source link

Call build on mailable when mocking and default to when sending emails #24538

Closed caiquecastro closed 6 years ago

caiquecastro commented 6 years ago

Description:

When I am testing mailables with Mail::fake() and Mail::assertSent(), and I use the second parameter for Mail::assertSent, the argument passed to the closure is missing the attributes, I would have to build it ($mail->build()). And if no recipient for the mail is not declared and would fallback to the default mail.to config, it's not on the returned object.

Steps To Reproduce:

Mail::fake();

Mail::assertSent(ContactForm::class, function ($mail) {
            return $mail->hasTo('example@example.com'); // this email is used from mail.to config.
});

I tried to add this custom config for email on laravel/laravel, but it was rejected:

https://github.com/laravel/laravel/pull/4672

themsaid commented 6 years ago

I don't seem to understand your issue, please share more details.

caiquecastro commented 6 years ago

Sorry If I was not clear.

In order for the test below to work, I have to build the mailable first.

// does not work
Mail::assertSent(ContactForm::class, function ($mail) {
    return $mail->hasTo('example@example.com');
});

// it works
Mail::assertSent(ContactForm::class, function ($mail) {
    $builtMail = $mail->build();
    return $builtMail->hasTo('example@example.com');
});

If this approach is OK, I think it's worthy to add a note on docs. What do you think?

deleugpn commented 6 years ago

I think somebody already tried a PR on this and was rejected because it's fair to just call the build method on the mailable.

caiquecastro commented 6 years ago

I think it's ok to call build, but I think it would be nice to have it documented. I want to know if it's the best practice.

laurencei commented 6 years ago

Please feel free to send a PR To the Laravel/Docs with the documentation idea :)