Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 access to Global Variables from a twig template in phpunit test

I have a twig template with {{ app.user }}. The problem is, that in a phpunit test (a class, which extends WebTestCase) it is defined as NULL. Simulating Authentication with a Token (http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html) or simulating HTTP Authentification (http://symfony.com/doc/current/cookbook/testing/http_authentication.html) does not help. So how can I set a twig global variable from a phpunit test? And why simulating authentification is not working in this case?

like image 659
Phantom Avatar asked May 06 '14 08:05

Phantom


1 Answers

I had a similar problem (logging in properly) what solved it finally for me was to change the way I log in(it's based on http://symfony.com/doc/current/cookbook/testing/simulating_authentication.html but I handle the session differently):

public function setUp() {
    parent::setUp();

    $this->em = $this->get('doctrine')->getManager();
    $this->client = static::createClient(array('environment' => 'test'));
}

protected function logIn() {
    $repo = $this->em->getRepository('XXXXXXX');
    $user = $repo->findOneByUsername('YYYYYYY');

    $session = new Session(new MockFileSessionStorage());
    $firewall = 'main';
    $token = new UsernamePasswordToken($user, null, $firewall, array('ROLE_ADMIN'));
    $this->client->getContainer()->get('security.context')->setToken($token);
    $session->set('_security_' . $firewall, serialize($token));
    $session->save();

    $this->client->getContainer()->set('session', $session);
    $cookie = new Cookie($session->getName(), $session->getId());
    $this->client->getCookieJar()->set($cookie);

    return $user;
}
like image 137
Bartłomiej Wach Avatar answered Nov 12 '22 10:11

Bartłomiej Wach