Last active
November 29, 2021 04:27
-
-
Save v-jacob/6113ac971a00611015c5 to your computer and use it in GitHub Desktop.
Mailhog PHPUnit Test Helper
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 | |
use GuzzleHttp\Client; | |
trait MailTestHelper | |
{ | |
/** | |
* @var \GuzzleHttp\Client | |
*/ | |
protected $client; | |
/** | |
* Setup guzzle client | |
*/ | |
public function setupMailTest() | |
{ | |
$this->$client = (new Client( | |
['base_uri' => 'http://127.0.0.1:8025/api/v1/'] | |
)); | |
$this->clearEmails(); | |
} | |
/** | |
* Get all the emails | |
* | |
* @return array | |
*/ | |
public function getAllEmails() | |
{ | |
$content = $this->client->get('messages')->getBody()->getContents(); | |
return json_decode($content, true); | |
} | |
/** | |
* Get last email sent | |
* | |
* @return array | |
*/ | |
public function getLastEmail() | |
{ | |
$lastEmailId = $this->getAllEmails()[0]['ID']; | |
$content = $this->client->get('messages/'.$lastEmailId)->getBody()->getContents(); | |
return json_decode($content, true); | |
} | |
/** | |
* Delete all emails | |
* | |
* @return mixed | |
*/ | |
public function clearEmails() | |
{ | |
return $this->client->delete('messages'); | |
} | |
/** | |
* Assert that email body contains the given string | |
* | |
* @param string $body | |
* @param array $response | |
*/ | |
public function assertEmailBodyContains($body, $response) | |
{ | |
$emailBody = $response['Content']['Body']; | |
// Get rid of strange equals character than can break your tests | |
$emailBody = html_entity_decode(str_replace("=\r\n", "", $emailBody), ENT_QUOTES); | |
$this->assertContains($body, $emailBody); | |
} | |
/** | |
* Assert that email subject equals the given string | |
* | |
* @param string $subject | |
* @param array $response | |
*/ | |
public function assertEmailSubjectIs($subject, $response) | |
{ | |
$emailSubject = $response['Content']['Headers']['Subject']; | |
$this->assertTrue( | |
in_array($subject, $emailSubject) | |
); | |
} | |
/** | |
* Assert that the email was send to given recipient | |
* | |
* @param string $recipient | |
* @param array $response | |
*/ | |
public function assertEmailWasSendTo($recipient, $response) | |
{ | |
$emailRecipient = $response['Content']['Headers']['To']; | |
$this->assertTrue( | |
in_array($recipient, $emailRecipient) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Need an update to works with last guzzle version