Skip to content

Instantly share code, notes, and snippets.

@v-jacob
Last active November 29, 2021 04:27
Show Gist options
  • Save v-jacob/6113ac971a00611015c5 to your computer and use it in GitHub Desktop.
Save v-jacob/6113ac971a00611015c5 to your computer and use it in GitHub Desktop.
Mailhog PHPUnit Test Helper
<?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)
);
}
}
@cgarnier
Copy link

cgarnier commented Jul 21, 2017

Need an update to works with last guzzle version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment