Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 testing with Mail::fake - how to access message body?

Tags:

php

laravel-5

I'm running Laravel 5.4 and testing Mailables with Mail::fake() and Mail::assertSent(). There are assertions for things like hasTo($email) and hasCc($email), but there doesn't seem to be a way to access the message contents. I would like to test that the email body contains a particular string.

Pseudocode:

Mail::assertSent(UserInvited::class, function($mail) use($token) {
    return $mail->bodyContains($token); # that method does not really exist
});

Is this possible?

like image 800
AdamTheHutt Avatar asked Feb 01 '17 20:02

AdamTheHutt


People also ask

How do I receive email in Laravel?

php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use App\Mail\SendMail; class SendEmailController extends Controller { public function index() { return view('send_email'); } function send(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' = ...

What is assertStatus in Laravel?

} The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.

What is mailable Laravel?

Laravel provides a clean, simple email API powered by the popular Symfony Mailer component. Laravel and Symfony Mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail , allowing you to quickly get started sending mail through a local or cloud based service of your choice.


2 Answers

Here is how I do it (along with helpful hints about how to do other stuff too):

Mail::fake(); //https://laravel.com/docs/5.7/mocking#mail-fake
$firstName = 'Sally';    
$self = $this;
Mail::assertQueued(MyMailable::class, function($mail) use($self, $firstName) {
    $mail->build(); // to set the email properties            
    $self->assertEquals($firstName, $mail->viewData["firstName"]);
    $self->assertEquals(["X-SES-CONFIGURATION-SET" => config('services.ses.options.ConfigurationSetName')], $mail->getHeaders());
    $self->assertTrue($mail->hasBcc(config('mail.supportTeam.address'), config('mail.supportTeam.name')));
    return true;
});
like image 60
Ryan Avatar answered Oct 11 '22 02:10

Ryan


Having run into the same situation and not having any luck with searches - after debugging:

Mail::assertSent(InstanceOfMailableEmail::class, function($mail) use ($needle) {

    // now your email has properties set
    $mail->build(); 

    //check the content body for a string
    return strpos($mail->viewData['content'], $needle) !== false;
});
like image 23
eithed Avatar answered Oct 11 '22 01:10

eithed