I'm trying to set up some testing for my REST API and I need to set a session variable inside the request object. The usual methods do not seem to work.
$session = $request->getSession();
$session->set('my_session_variable', 'myvar');
You should use WebTestCase
Then you can do things which are described in answer for similar question: how-can-i-persist-data-with-symfony2s-session-service-during-a-functional-test
so something like:
$client = static::createClient();
$container = $client->getContainer();
$session = $container->get('session');
$session->set('name', 'Sensorario');
$session->save();
Fatal error: Call to a member function getContainer() on a non-objectIf you use WebTestCase, 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('my_session_variable', 'myvar'); // 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( .... ...
A short snippet to set some value in session
$session = $this->client->getRequest()->getSession();
$session->set('name', 'Sensorario');
And a very very simple example to get this value
echo $session->get('name');