Skip to content

Instantly share code, notes, and snippets.

@bgdevlab
Forked from v-jacob/MailTestHelper.php
Last active November 29, 2021 04:44
Show Gist options
  • Save bgdevlab/bfd7dd483475f070f2490a1f98bfc591 to your computer and use it in GitHub Desktop.
Save bgdevlab/bfd7dd483475f070f2490a1f98bfc591 to your computer and use it in GitHub Desktop.
Mailhog PHPUnit Test Helper
<?php
namespace Tests\Traits;
use GuzzleHttp\Client;
trait MailHogTestHelper
{
/**
* @var \GuzzleHttp\Client
*/
protected $client;
protected $MAILHOG_API='http://127.0.0.1:8025/api/v1/';
/**
* Setup guzzle client
*/
public function setupMailTest()
{
$this->client = (new Client(
['base_uri' => $this->MAILHOG_API]
));
$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