Skip to content

Commit 86dfeee

Browse files
committed
Merge branch '5.2' into 5.x
* 5.2: Restored a section wrongly removed while upmerging
2 parents 90754dd + f320bcf commit 86dfeee

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

testing.rst

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,65 @@ will no longer be followed::
572572

573573
$client->followRedirects(false);
574574

575+
.. _testing_logging_in_users:
576+
577+
Logging in Users (Authentication)
578+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
579+
580+
.. versionadded:: 5.1
581+
582+
The ``loginUser()`` method was introduced in Symfony 5.1.
583+
584+
When you want to add application tests for protected pages, you have to
585+
first "login" as a user. Reproducing the actual steps - such as
586+
submitting a login form - make a test very slow. For this reason, Symfony
587+
provides a ``loginUser()`` method to simulate logging in in your functional
588+
tests.
589+
590+
Instead of logging in with real users, it's recommended to create a user only for
591+
tests. You can do that with Doctrine :ref:`data fixtures <user-data-fixture>`,
592+
to load the testing users only in the test database.
593+
594+
After loading users in your database, use your user repository to fetch
595+
this user and use
596+
:method:`$client->loginUser() <Symfony\\Bundle\\FrameworkBundle\\KernelBrowser::loginUser>`
597+
to simulate a login request::
598+
599+
// tests/Controller/ProfileControllerTest.php
600+
namespace App\Tests\Controller;
601+
602+
use App\Repository\UserRepository;
603+
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
604+
605+
class ProfileControllerTest extends WebTestCase
606+
{
607+
// ...
608+
609+
public function testVisitingWhileLoggedIn()
610+
{
611+
$client = static::createClient();
612+
$userRepository = static::$container->get(UserRepository::class);
613+
614+
// retrieve the test user
615+
$testUser = $userRepository->findOneByEmail('[email protected]');
616+
617+
// simulate $testUser being logged in
618+
$client->loginUser($testUser);
619+
620+
// test e.g. the profile page
621+
$client->request('GET', '/profile');
622+
623+
$this->assertResponseIsSuccessful();
624+
$this->assertSelectorTextContains('h1', 'Hello John!');
625+
}
626+
}
627+
628+
You can pass any
629+
:class:`Symfony\\Component\\Security\\Core\\User\\UserInterface` instance to
630+
``loginUser()``. This method creates a special
631+
:class:`Symfony\\Bundle\\FrameworkBundle\\Test\\TestBrowserToken` object and
632+
stores in the session of the test client.
633+
575634
Making AJAX Requests
576635
....................
577636

0 commit comments

Comments
 (0)