Nathan
Nathan

Reputation: 666

Symfony tests not calling my LoginSubscriber

I'm using Symfony 6.4, and I have a LoginSubcriber which sets some additional session data depending on the authenticated user's account setup. This additional session data is essential for the running of the site.

My subscriber is registered in /config/services.yaml as such:

services:
  ...
  App\EventListener\LoginSubscriber:
    tags: [ name: kernel.event_subscriber ]

And it works perfectly when logging in via a browser.

My issue comes when testing. If I call login $client->loginUser($user), then my LoginSubscriber is never called, which makes subsequent requests not work properly because they don't have the correct session data setup within the LoginSubscriber.

As a way around this, I changed my test to log the user in manually by going through the full flow:

class FullSearchTest extends WebTestCase
{
    public function testPartialSearchRequiresThreeCharacters(): void
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/');
        $form = $crawler->selectButton('SIGN IN')->form([
            '_username' => 'admin',
            '_password' => 'password',
        ]);
        $client->submit($form);
        $client->followRedirects();

        $client->request('GET', '/search', [
            'firstName' => 'fo',
        ]);

        $this->assertResponseIsUnprocessable();
    }
}

I run the test with phpunit like php bin/phpunit

The route /search requires the ROLE_USER, so they must be logged in.

I guess my question is, is there a way to get $client->loginUser($user); to trigger the LoginSubscriber, and if not, is my manual login workaround efficient in the long term, as I add more and more tests?

Upvotes: 0

Views: 66

Answers (0)

Related Questions