Search code examples
authenticationtestingsymfonyfunctional-testing

How to functional test secured pages in Symfony2?


Setup and information to reproduce the problem

  • Symfony2.2 application
  • LiipFunctionalTestBundle
  • DoctrineFixturesBundle
  • FOSUserBundle

For testing enviroment I use LiipFunctionalTestBundle and generate (from DoctrineFixtures) a fake SQLite database. It's configured correctly - I've been able to succesfully test my non-secured pages.

I've created a simple secured page under /secured/test with this view:

<h2 class="username">{{ app.user.username }}</h2>
  1. I've tried with

And I wanted to test this action with this assertion:

$client = static::createClient(array(), array(
    'PHP_AUTH_USER' => 'myUserName'
    'PHP_AUTH_PW'   => 'password',
));

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

$count = $crawler
         ->filter('h2.username:contains("myUserName")')
         ->count();

$this->assertTrue($count > 0);

The result was Failed asserting that false is true.

  1. I've tried with

And I wanted to test this action with this assertion:

$this->logIn();

$crawler = $this->client->request('GET', '/secured/test');

$count = $crawler
         ->filter('h2.username:contains("myUserName")')
         ->count();

$this->assertTrue($count > 0);

Ofcourse I changed the logIn function to diffrent username.

The result was Failed asserting that false is true.

None of these works. Whats wrong?

I've tried many other methods, but


Solution

  • The solution to the problem was very simple:

    In my DoctrineFixtures I've created new users.. but their accounts were not enabled.

    Adding this code to fixture solved the problem:

        $user->setEnabled(true);
        $user->setExpired(false);
        $user->setLocked(false);
    

    (becouse my test was trying to log on not enabled account, the response to "submit login form" was redirect to login page)