Created
June 14, 2016 22:02
-
-
Save sahibalejandro/23511da08badec951a74bf61ab79bf4c to your computer and use it in GitHub Desktop.
Trait for test emails using mailcatcher
This file contains 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 App\Testing; | |
use GuzzleHttp\Client; | |
trait Emails | |
{ | |
/** | |
* Assert last email from mailcatcher is sent from a specified address. | |
* | |
* @param string $email | |
* @return $this | |
*/ | |
protected function seeEmailSentFrom($email) | |
{ | |
$sender = $this->getLastEmail()['sender']; | |
$this->assertEquals("<$email>", $sender); | |
return $this; | |
} | |
/** | |
* Assert last email from mailcatcher is sent to a specified address. | |
* | |
* @param string $email | |
* @return $this | |
*/ | |
protected function seeEmailSentTo($email) | |
{ | |
$recipients = $this->getLastEmail()['recipients']; | |
$this->assertTrue(in_array("<$email>", $recipients)); | |
return $this; | |
} | |
/** | |
* Assert that the last email from mailcatcher contains a specified text. | |
* | |
* @param string $text | |
* @return $this | |
*/ | |
protected function seeEmailContains($text) | |
{ | |
// Grab the last email ID. | |
$id = last($this->getAllEmails())['id']; | |
// Get the last email contents. | |
$email = $this->mailcatcher()->get("/messages/{$id}.html") | |
->getBody() | |
->getContents(); | |
// Finally assert that email contains the message. | |
$this->assertContains($text, $email); | |
return $this; | |
} | |
/** | |
* Returns an instance of GuzzleHttp\Client ready to query mailcatcher API. | |
* | |
* @return \GuzzleHttp\Client | |
*/ | |
protected function mailcatcher() | |
{ | |
return new Client(['base_uri' => 'http://127.0.0.1:1080']); | |
} | |
/** | |
* Gets all emails from mailcatcher. | |
* | |
* @return array | |
*/ | |
protected function getAllEmails() | |
{ | |
// Grab all messages from mailcatcher as an array. | |
$emails = json_decode( | |
$this->mailcatcher()->get('/messages')->getBody()->getContents(), | |
true | |
); | |
// If there is no messages then the test will fail. | |
if (empty($emails)) { | |
$this->fail('No emails found.'); | |
} | |
return $emails; | |
} | |
/** | |
* Get the last email. | |
* | |
* @return array | |
*/ | |
protected function getLastEmail() | |
{ | |
return last($this->getAllEmails()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment