Last active
October 19, 2018 10:10
-
-
Save johnhout/3b6ca6cbc7ecb4bbf2bfb9ec430b031c to your computer and use it in GitHub Desktop.
Mailtrap test trait for PHPUnit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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