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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With