New in Symfony 5.1: Simpler login in tests
March 23, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Wouter De Jong
in #35997.
In functional tests, testing protected pages requires logging in as a user. Reproducing the actual login process (e.g. typing a username and password in a login form and submitting it) makes tests slow. Symfony recommends this trick as a faster alternative, but it may not fit your needs.
That's why in Symfony 5.1 we've added a new loginUser()
method to simulate
the full user login inside a test. Pass the UserInterface
object of the
user you want to login and that's all:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// tests/Controller/ProfileControllerTest.php
namespace App\Tests\Controller;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ProfileControllerTest extends WebTestCase
{
// ...
public function testVisitingWhileLoggedIn()
{
$client = static::createClient();
// get or create the user somehow (e.g. creating some users only
// for tests while loading the test fixtures)
$userRepository = static::$container->get(UserRepository::class);
$testUser = $userRepository->findOneByEmail('jane.doe@example.com');
$client->loginUser($testUser);
// user is now logged in, so you can test protected resources
$client->request('GET', '/profile');
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('h1', 'Hello Username!');
}
}
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.