Bildiğimiz gibi, test ortamında genelde email gördermeyiz, onun yerine, symfony'nin "spool" klasöründe emaili bir dosya olarak saklarız. Aşağıdaki örneği kullanarak emailin gönderilip gönderilmediğini test edebilirsiniz. Not: Göndereceğiniz emaillere X-Message-ID ekini mutlaka ekleyiniz. Mesela aşağıdaki örnekte $message->getHeaders()->addTextHeader('X-Message-ID', 'registration'); ekini kullanıyoruz.


Config_test.php


swiftmailer:
disable_delivery: true
spool:
type: file
path: %kernel.cache_dir%/spool

Gherkin feature


Feature: Dummy feature

Scenario: I can test spool emails
Given I am on "/"
Then the "registration" mail sent to "customer@customer.com" should contain:
"""
Registration

Hello,

Thank you for registering with us.

inanzzz
"""

FeatureContext.php


namespace Application\FrontendBundle\Features\Context;

use Behat\Gherkin\Node\PyStringNode;
use Behat\MinkExtension\Context\MinkContext;
use Behat\Symfony2Extension\Context\KernelAwareContext;
use Exception;
use Swift_Message;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\KernelInterface;

class FeatureContext extends MinkContext implements KernelAwareContext
{
private $kernel;

public function setKernel(KernelInterface $kernelInterface)
{
$this->kernel = $kernelInterface;
}

/**
* @param string $messageId
* @param string $toEmailAddress
* @param PyStringNode $contains
*
* @throws Exception
*
* @Then /^the "([^"]*)" mail sent to "([^"]*)" should contain:$/
*/
public function theMailSentToShouldContain($messageId, $toEmailAddress, PyStringNode $contains)
{
$spoolDir = $this->getSpoolDir();
$filesystem = new Filesystem();
$spoolMessage = null;

if ($filesystem->exists($spoolDir)) {
$finder = new Finder();
$finder
->in($spoolDir)
->ignoreDotFiles(true)
->files();

foreach ($finder as $file) {
/** @var Swift_Message $message */
$message = unserialize(file_get_contents($file));

$recipients = array_keys($message->getTo());
if (!in_array($toEmailAddress, $recipients)) {
continue;
}

$headers = $message->getHeaders();
if ($headers->has('X-Message-ID')) {
if ($headers->get('X-Message-ID')->getValue() == $messageId) {
$spoolMessage = $message->getBody();
break;
}
}
}
}

if ($spoolMessage === null || trim(strip_tags($spoolMessage)) != $contains->getRaw()) {
throw new Exception(sprintf('The message with ID ["%s"] was not sent.', $messageId));
}
}

/**
* We need to purge the spool between each scenario
*
* @BeforeScenario
*/
public function purgeSpool()
{
$spoolDir = $this->getSpoolDir();

$filesystem = new Filesystem();
$filesystem->remove($spoolDir);
}

/**
* @return string
*/
private function getSpoolDir()
{
return $this->kernel->getContainer()->getParameter('swiftmailer.spool.default.file.path');
}
}