Skip to content

Instantly share code, notes, and snippets.

@cgarnier
Forked from v-jacob/MailTestHelper.php
Last active May 17, 2022 10:24
Show Gist options
  • Save cgarnier/8fabb714f583a6b1bf10882fd4028171 to your computer and use it in GitHub Desktop.
Save cgarnier/8fabb714f583a6b1bf10882fd4028171 to your computer and use it in GitHub Desktop.
Mailhog PHPUnit Test Helper
<?php
use GuzzleHttp\Client;
trait MailTestHelper
{
/**
* @var \GuzzleHttp\Client
*/
protected $mailService;
/**
* Setup guzzle client
*/
public function setupMailTest()
{
$this->mailService = (new Client());
$this->clearEmails();
}
/**
* Get all the emails
*
* @return array
*/
public function getAllEmails()
{
return json_decode($this->mailService->get(self::MAILHOG_API . 'messages')->getBody());
}
/**
* Get last email sent
*
* @return object
*/
public function getLastEmail()
{
$lastEmailId = $this->getAllEmails()[0]->ID;
return json_decode($this->mailService->get(self::MAILHOG_API . 'messages/'.$lastEmailId)->getBody());
}
/**
* Delete all emails
*
* @return mixed
*/
public function clearEmails()
{
return $this->mailService->delete(self::MAILHOG_API . 'messages');
}
/**
* Assert that email body contains the given string
*
* @param string $body
* @param object $email
*/
public function assertEmailBodyContains($body, $email)
{
$emailBody = $email->Content->Body;
// Get rid of strange equals character than can break your tests
$emailBody = str_replace("=\r\n", "", $emailBody);
$this->assertContains($body, $emailBody);
$this->assertContains(
$body,
$emailBody
);
}
/**
* Assert that email subject equals the given string
*
* @param string $subject
* @param object $email
*/
public function assertEmailSubjectIs($subject, $email)
{
$emailSubject = $email->Content->Headers->Subject;
$this->assertContains($subject, $emailSubject);
}
/**
* Assert that the email was send to given recipient
*
* @param string $recipient
* @param object $email
*/
public function assertEmailWasSendTo($recipient, $email)
{
$emailRecipient = $email->Content->Headers->To;
$this->assertContains($recipient, $emailRecipient);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment