|
| 1 | +.. index:: |
| 2 | + single: Emails; Testing |
| 3 | + |
| 4 | +How to test that an Email is sent in a functional Test |
| 5 | +====================================================== |
| 6 | + |
| 7 | +Sending e-mails with Symfony2 is pretty straightforward thanks to the |
| 8 | +``SwiftmailerBundle``, which leverages the power of the `Swiftmailer`_ library. |
| 9 | + |
| 10 | +To functionally test that an email was sent, and even assert the email subject, |
| 11 | +content or any other headers, you can use :ref:`the Symfony2 Profiler <internals-profiler>`. |
| 12 | + |
| 13 | +Start with an easy controller action that sends an e-mail:: |
| 14 | + |
| 15 | + public function sendEmailAction($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 the profiler as explained in :doc:`/cookbook/testing/profiling`. |
| 32 | + |
| 33 | +In your functional test, use the ``swiftmailer`` collector on the profiler |
| 34 | +to get information about the messages send on the previous request:: |
| 35 | + |
| 36 | + // src/Acme/DemoBundle/Tests/Controller/MailControllerTest.php |
| 37 | + use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; |
| 38 | + |
| 39 | + class MailControllerTest extends WebTestCase |
| 40 | + { |
| 41 | + public function testMailIsSentAndContentIsOk() |
| 42 | + { |
| 43 | + $client = static::createClient(); |
| 44 | + $crawler = $client->request('POST', '/path/to/above/action'); |
| 45 | + |
| 46 | + $mailCollector = $client->getProfile()->getCollector('swiftmailer'); |
| 47 | + |
| 48 | + // Check that an e-mail was sent |
| 49 | + $this->assertEquals(1, $mailCollector->getMessageCount()); |
| 50 | + |
| 51 | + $collectedMessages = $mailCollector->getMessages(); |
| 52 | + $message = $collectedMessages[0]; |
| 53 | + |
| 54 | + // Asserting e-mail data |
| 55 | + $this->assertInstanceOf('Swift_Message', $message); |
| 56 | + $this->assertEquals('Hello Email', $message->getSubject()); |
| 57 | + $this->assertEquals('send@example.com', key($message->getFrom())); |
| 58 | + $this->assertEquals('recipient@example.com', key($message->getTo())); |
| 59 | + $this->assertEquals('You should see me from the profiler!', $message->getBody()); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +.. _Swiftmailer: http://swiftmailer.org/ |
0 commit comments