Search code examples
symfonyphpunitsymfony-2.3

symfony2 test flashbag or session data


How do you test for FlashBag message?

Tried this:

public function testInvalidLogin()
{
    $session = $this->client->getContainer()->get('session');
    $crawler = $this->client->request('GET', '/login');

    $this->assertTrue($this->client->getResponse()->isSuccessful());
    $form = $crawler->filter('form');
    $this->assertGreaterThan(0, $form->count());

    $form = $form->form();
    $this->assertNotEmpty($form);

    $form['_username'] = 'username';
    $form['_password'] = 'password';

    $this->client->submit($form);
    $this->assertTrue($this->client->getResponse()->isRedirect('http://localhost/login'));
    $this->client->followRedirect();

    $session = $this->client->getContainer()->get('session');
    var_dump($session->getBag('flashes')->all()); // this print an empty array
}

The login controller is sets a flash message 'Bad credentials' but i'm not able to see it during the tests.


Solution

  • Probably it's because after your redirection you are poping flash message eg. somewhere in your template. Flash bag container remove flash message just after you call get method (to be specified - removing is implemented IN get method...). If you want just get the message without poping it you should use peek method.

    I guess that if you move var_dump before followRedirect then you will get the result you are expecting.