Skip to content

Instantly share code, notes, and snippets.

@johnhout
Last active October 19, 2018 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnhout/3b6ca6cbc7ecb4bbf2bfb9ec430b031c to your computer and use it in GitHub Desktop.
Save johnhout/3b6ca6cbc7ecb4bbf2bfb9ec430b031c to your computer and use it in GitHub Desktop.
Mailtrap test trait for PHPUnit
<?php
namespace Tests;
use GuzzleHttp\Client;
trait MailtrapTrait
{
public $mailtrap;
protected $mailtrap_inbox;
public function usesMailtrap()
{
// Create connection mailtrap.io
$this->mailtrap = new Client(
[
'base_uri' => getenv('MAILTRAP_API_BASE_URI'),
'headers' => [
'Api-Token' => getenv('MAILTRAP_API_TOKEN'),
],
]
);
$this->mailtrap_inbox = getenv('MAILTRAP_API_INBOX');
// Clean messages of mailtrap between each tests
$this->cleanMessages();
}
public function assertEmailIsSent($description = '')
{
$this->assertNotEmpty($this->getMessages(), $description);
}
/**
* Clean Messages of the mailtrap inbox.
*/
protected function cleanMessages()
{
$this->mailtrap->request('PATCH', "inboxes/$this->mailtrap_inbox/clean");
}
/**
* Fetch the last message received in mailtrap inbox.
*
* @return object Message
*/
protected function getLastMessage()
{
$messages = $this->getMessages();
if (empty($messages)) {
$this->fail('Api Mailtrap: No messages found.');
}
return $messages[0];
}
/**
* Fetch messages of the mailtrap inbox.
*
* @return json The messages of the inbox given
*/
protected function getMessages()
{
$response = $this->mailtrap->request('GET', "inboxes/$this->mailtrap_inbox/messages");
return json_decode((string) $response->getBody());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment