Search code examples
ajaxsymfonyphpunitfosuserbundlefunctional-testing

Symfony2 functional test with Session and Post


I am trying to write some Symfony2 functional tests, using PHPUnit, that simulate a logged-in user requesting some resource via an AJAX call.

The test first simulates a user logging-in using the standard FOSUserBundle log-in form;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MyWebTestCase extends WebTestCase {

public function login($username, $password = 'password')
{
    $client = static::createClient();
    $client->followRedirects(true);
    $crawler = $client->request('GET', '/login');

    $form = $crawler->selectButton('Login')->form(array(
        '_username' => $username,
        '_password' => $password,
    ));

    $crawler = $client->submit($form);

    return $client;
}
}

Then, the test gets an entity from the database and sets it in a session variable, then sends a POST request to retrieve the requested resource, using some JSON which includes extra information about what is being requested (in the actual application, some JavaScript composes the JSON in response to the user's actions which is then submitted via AJAX);

    $this->client = $this->login('[email protected]', 'password');

    // we want element number 6 from the fixtures
    $chart = $this->em->getRepository('MyBundle:Element')->find(6);

    $guid = $chart->getGuid();

    $this->client->getContainer()->get('session')->set($guid, $chart);

    $link = sprintf('/viewer/data/%d/%s', 1, $guid);

    $crawler = $this->client->request('POST', $link, array(), array(),
        array('CONTENT_TYPE' => 'application/json'),
        '{"filters":[]}');

When the tests reach this point, an error is generated;

ini_set(): A session is active. You cannot change the session module's ini settings at this time

I'm using Symfony 2.6.5 and PHPUnit 4.5.0


Solution

  • Do you use mock sessions for your test? If not try this.

    Config_test.yml

    framework:
       test: ~
       session:
          storage_id: session.storage.mock_file
    

    The native session storage is meant to handle a single request per process which may lead to your bug. if its your case.