0

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');

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response, I've tried that and read that article but I still get this: Fatal error: Call to a member function getContainer() on a non-object
1

If you use WebTestCase, you can retrieve the "session" service. With this service, you can :

  • start the session,
  • set some parameters into session,
  • save the session,
  • pass the Cookie with sessionId to the request

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( .... ...

Comments

-1

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');

2 Comments

doesn't work... I have to manually create the request variable as it's coming from CLI
There is no $this->getRequest() in tests. And $this->$client->getRequest() in null before you did any request. So, it will not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.