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?
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' = ...
} 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.
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.
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;
});
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With