In addition to verifying the structural and syntactical correctness of your Twig template files by linting them, you can also unit test the logic of your Twig templates.
For example, you can verify the correct behaviour of an if-elseif-else-endif
construct, and you can do so in isolation, that is, without the need to go through controllers with all their dependencies.
Have a look at https://github.com/journeymonitor/control/blob/2645c69/src/AppBundle/Resources/views/testcases/_testresults-overview-testresult-label.html.twig. It's a very simple template, but it does have some amount of behaviour - depending on the value of testresult.exitCode
, different label names must be output.
At https://github.com/journeymonitor/control/blob/bc42e78/tests/AppBundle/Resources/views/testcases/_testresults-overview-testresult-label.html.twig.test.php, you can see the unit test case for this template.
The test case sets up a new Twig_Environment
, which enables you to load the Twig template file and render
it with different Testresult
objects passed in as a parameter. The result of the render operation can then be asserted as in any other PHPUnit test:
$loader = new Twig_Loader_Filesystem(__DIR__ . '/../../../../../src/AppBundle/Resources/views/testcases/');
$twig = new Twig_Environment($loader, array(
'cache' => '/var/tmp/journeymonitor-twig-tests-cache',
));
$template = $twig->loadTemplate('_testresults-overview-testresult-label.html.twig');
$testresult = new \AppBundle\Entity\Testresult();
$testresult->setExitCode(0);
$this->assertSame('success', $template->render(['testresult' => $testresult]));
Note the shell commands on line 8 and 9 - the Twig environment caches its template files, and in order to have reliable tests, you need to ensure that the cache location is wiped before each test run:
`rm -rf /var/tmp/journeymonitor-twig-tests-cache`;
`mkdir -p /var/tmp/journeymonitor-twig-tests-cache`;
php app/console twig:lint <file>
. – cmt Jun 10 '13 at 15:42