Reputation: 25295
I'm writing a functional test for an action that uses Symfony2's session service to fetch data. In my test class's setUp
method, I call $this->get('session')->set('foo', 'bar');
. If I output all the session data (using print_r($this->get('session')->all());
) either in setUp
or in the actual test method, I get back foo => bar
. But if I try outputting the session data from the action being tested, I get back an empty array. Does anyone know why this is happening, and how I can prevent it?
I should note that if I call $_SESSION['foo'] = 'bar'
from within setUp()
the data is persisted and I can access it from the action - this problem seems local to Symfony2's session service.
Upvotes: 4
Views: 2030
Reputation: 1359
You can retrieve the "session" service. With this service, you can :
The code can be the following :
use Symfony\Component\BrowserKit\Cookie;
....
....
public function testARequestWithSession()
{
$client = static::createClient();
$session = $client->getContainer()->get('session');
$session->start(); // optional because the ->set() method do the start
$session->set('foo', 'bar'); // the session is started here if you do not use the ->start() method
$session->save(); // important if you want to persist the params
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId())); // important if you want that the request retrieve the session
$client->request( .... ...
The Cookie with $session->getId() has to be created after the start of the session
See Documentation http://symfony.com/doc/current/testing/http_authentication.html#creating-the-authentication-token
Upvotes: 0
Reputation: 36191
Firstly try using your client's container (I'm assuming you're using WebTestCase):
$client = static::createClient();
$container = $client->getContainer();
If it still doesn't work try saving the session:
$session = $container->get('session');
$session->set('foo', 'bar');
$session->save();
I didn't try it in functional tests but that's how it works in Behat steps.
Upvotes: 7