|
| 1 | +.. index:: |
| 2 | + single: Emails; Testing |
| 3 | + |
| 4 | +How to functionally test an Email is sent |
| 5 | +========================================= |
| 6 | + |
| 7 | +Sending e-mails with Symfony2 is pretty straight forward thanks to the |
| 8 | +``SwiftmailerBundle``, which leverages the power of the `Swiftmailer`_ library. |
| 9 | + |
| 10 | +To functionally test that e-mails are sent, and even assert their subjects, |
| 11 | +content or any other headers we can use :ref:`the Symfony2 Profiler <internals-profiler>`. |
| 12 | + |
| 13 | +Let's start with an easy controller action that sends an e-mail:: |
| 14 | + |
| 15 | + public function indexAction($name) |
| 16 | + { |
| 17 | + $message = \Swift_Message::newInstance() |
| 18 | + ->setSubject('Hello Email') |
| 19 | + ->setFrom('send@example.com') |
| 20 | + ->setTo('recipient@example.com') |
| 21 | + ->setBody('You should see me from the profiler!') |
| 22 | + ; |
| 23 | + |
| 24 | + $this->get('mailer')->send($message); |
| 25 | + |
| 26 | + return $this->render(...); |
| 27 | + } |
| 28 | + |
| 29 | +.. note:: |
| 30 | + |
| 31 | + Don't forget to enable profiler as explained in :doc:`/cookbook/testing/profiling`. |
| 32 | + |
| 33 | +And the ``WebTestCase`` to assert the e-mail content should be similar to:: |
| 34 | + |
| 35 | + // src/Acme/DemoBundle/Tests/Controller/MailControllerTest.php |
| 36 | + use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; |
| 37 | + |
| 38 | + class MailControllerTest extends WebTestCase |
| 39 | + { |
| 40 | + public function testMailIsSentAndContentIsOk() |
| 41 | + { |
| 42 | + $client = static::createClient(); |
| 43 | + $crawler = $client->request('GET', 'your_action_route_here'); |
| 44 | + |
| 45 | + $mailCollector = $client->getProfile()->getCollector('swiftmailer'); |
| 46 | + |
| 47 | + // Check that an e-mail was sent |
| 48 | + $this->assertEquals(1, $mailCollector->getMessageCount()); |
| 49 | + |
| 50 | + $collectedMessages = $mailCollector->getMessages(); |
| 51 | + $message = $collectedMessages[0]; |
| 52 | + |
| 53 | + // Asserting e-mail data |
| 54 | + $this->assertInstanceOf('Swift_Message', $message); |
| 55 | + $this->assertEquals('Hello Email', $message->getSubject()); |
| 56 | + $this->assertEquals('send@example.com', key($message->getFrom())); |
| 57 | + $this->assertEquals('recipient@example.com', key($message->getTo())); |
| 58 | + $this->assertEquals('You should see me from the profiler!', $message->getBody()); |
| 59 | + } |
| 60 | + } |
| 61 | + |
0 commit comments