Skip to content

Instantly share code, notes, and snippets.

@sileence
Last active September 7, 2018 19:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sileence/85298aa1a5f6a24026caba72fbdf5c88 to your computer and use it in GitHub Desktop.
Save sileence/85298aa1a5f6a24026caba72fbdf5c88 to your computer and use it in GitHub Desktop.
Little trick to test and inspect the body of the mailable classes
<?php
//Usage:
//$token = factory(etc...);
$this->open(new TokenMail($token))
->seeLink($token->url, $token->url);
  • Add the trait InteractsWithMailable in your tests/ folder

  • Autoload it with Composer:

    "autoload-dev": { "classmap": [ "tests/InteractsWithMailable.php" ] },

  • Execute composer dump-autoload in the console

  • Include the trait InteractsWithMailable in the classes you want to test mailables.

  • Don't mix up visit() and open() since open() will overwrite the crawler.

  • If Laravel tells you the array driver is not supported, please execute composer update to make sure you have the latest Laravel 5.3 version.

<?php
use Illuminate\Contracts\Mail\Mailable;
use Symfony\Component\DomCrawler\Crawler;
trait InteractsWithMailable
{
protected function open(Mailable $mailable)
{
$this->app->make('config')->set('mail.driver', 'array');
$this->mailTransport()->flush();
$this->app->make('mailer')->send($mailable);
$mail = $this->swiftMessages()->first();
$this->crawler = new Crawler($mail->getBody());
return $this;
}
protected function swiftMessages()
{
$messages = $this->mailTransport()->messages();
$this->assertNotEmpty($messages, 'No messages were sent');
return $messages;
}
protected function mailTransport()
{
return $this->app->make('mailer')->getSwiftMailer()->getTransport();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment