phpunit-testingtwigphpunitslim

testing twig with phpunit


I want to implement some unit tests with Twig and PHPUnit(both installed with composer, with slim/views added). But when I try to test a template generation, it blocks at {{ baseUrl() }}. But the templates works fine when I test it on the navigator, without phpunit.

here is the error message :

Twig_Error_Runtime: An exception has been thrown during the rendering of a template 
("Undefined index: REQUEST_METHOD") in "application/General.twig" at line 21.

Solution

  • As described in this article, It’s not so easy to write Test Cases for slim framework. You could mock the SLIM Environment as follow:

    // Prepare a mock environment
            Environment::mock(array_merge(array(
                'REQUEST_METHOD' => $method,
                'PATH_INFO' => $path,
                'SERVER_NAME' => 'slim-test.dev',
            ), $options));
            $app = new \Slim\Slim();
            $this->app = $app;
            $this->request = $app->request();
            $this->response = $app->response();
    

    Full code example in this gist

    Hope this help