Twig is_granted fails in Behat scenario

Viewed 164

I have this Behat setup:

default:
    extensions:
        Behat\Symfony2Extension: ~
        Behat\MinkExtension:
            sessions:
                default:
                    symfony2: ~

And this scenarion:

Scenario: Event list for authenticated user
  Given I am authenticated
   Then I should see pagination control
    And I should be able to change list page

I check if the user is authenticated and if so show him pagination control in Twig:

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
...

Related Behat context:

/**
 * @Given I am authenticated
 */
public function iAmAuthenticated()
{
    $user = new User('test', null, ['ROLE_USER']);
    $token = new UsernamePasswordToken($user, null, 'test', $user->getRoles());

    $this->getTokenStorage()->setToken($token);
}


/**
 * @Then I should see pagination control
 */
public function iShouldSeePaginationControl()
{
    $this->assertSession()->elementExists('css', 'ul.pagination');
}

I get true for

$this->kernel
    ->geContainer()
    ->get('security.authorization_checker')
    ->isGranted('IS_AUTHENTICATED_FULLY') 

in my iShouldSeePaginationControl() but it is false in rendered content.

What am I missing?

2 Answers

My guess is that you're using a different instance of the container in your behat step and in your template.

AFAIR, the symfony2 driver uses BrowserKit under the hood to navigate through your website. The container which will be used in your web page will then be instanciated by the PHP Engine of your Web server (and not by Behat). If so, it is absolutely impossible to operate modifications in the container at runtime in a step and expect that the web server will be aware of them.

Easy solution would be to actually log in in the behat step (through the web interface) instead of setting the token manually.

Another harder way, if you absolutely want to login programatically, would be to serialize the created token on HDD and register some kind of logic (a kernel.request listener for example) that will check if this file is available and inject the unserialized token in the security context. If you do so, MAKE SURE that you enable this logic in TEST environment only, as it potentially is a security breach.

Related