user3348802
user3348802

Reputation: 151

Symfony2 functional test session persistence

I'm trying to play a little bit with the functional test in Symfony and i'm currently facing a problem with my sessions. I execute a piece of code, which seems to be working, but nothing is stored inside the session of my container.

I have a form where you set datas. When you submit it, it checks the values and store it inside sessions. Then it redirects to another page where these values stored in session are needed.

The purpose of my test is to check the session.

<?php

namespace Acme\TestBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;

class FrontControllerTest extends WebTestCase
{
    public function testForm()
    {
        $client = static::createClient();
        $session = $client->getContainer()->get('session');

        $crawler = $client->request('GET', '/setParameters');

        $form = $crawler->selectButton('Submit')->form();
        $form['myForm[firstname]']->setValue('Ben');
        $form['myForm[lastname]']->setValue('H');

        $client->submit($form);

        //I tested and my controller is fully going through the submit handler
        //which check the values and save it into the session
        //Things are 100% sure there. Then it redirects to another page which check those values.

        $values = $client->getContainer()->get('session')->get('parameters'); //NULL
        $this->assertEquals($values['firstname'], 'Ben'); //false
        $this->assertEquals($values['lastname'], 'H'); //false
    }
}

Actually it's not working at all, it seems like i can't store anything in the session and retrieve it.

Can someone help me with it ? Thank's.

Upvotes: 3

Views: 1617

Answers (1)

sebbo
sebbo

Reputation: 2939

The container you use in your test is not the container that is used by the requests you trigger. Symfony creates new containers for each request. So you can not access the session directly via the container.

See also http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests

A possible solution would be to extract the session ID from your cookies and then read the session from your session storage.

Upvotes: 2

Related Questions