Skip to content

Commit f9c548e

Browse files
committed
Update documentation for WithAuthenticationTrait
1 parent 7c71798 commit f9c548e

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

README.md

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,56 @@ class MyCoolTest extends WebTestCase
110110
{
111111
$client = static::createClient();
112112

113-
$this->authenticate($client, 'my_firewall_name');
113+
// Authenticate with dummy username, don't need the user to exist in the database
114+
$this->authenticate($client, "fakeUserName", 'my_firewall_name');
114115
$client->request('GET', '/protected/route');
115116

116-
$this->authenticate($client, 'my_firewall_name', ['ROLE_ADMIN']);
117+
// You can pass custom roles for your simulated user
118+
$this->authenticate($client, "fakeUserName", 'my_firewall_name', ['ROLE_ADMIN']);
117119
$client->request('GET', '/admin/foo');
118120

119-
$this->authenticateAsAdmin($client, 'my_firewall_name');
121+
// A shortcut to authenticate as an admin
122+
$this->authenticateAsAdmin($client, "fakeUserName", 'my_firewall_name');
123+
$client->request('GET', '/admin/foo');
124+
}
125+
}
126+
```
127+
128+
You can also authenticate with a real user !
129+
130+
```php
131+
<?php
132+
133+
use Liior\SymfonyTestHelpers\Concerns\WithAuthenticationTrait;
134+
use Liior\SymfonyTestHelpers\Concerns\WithDatabaseTrait;
135+
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
136+
use App\Entity\User;
137+
138+
class MyCoolTest extends WebTestCase
139+
{
140+
use WithAuthenticationTrait;
141+
use WithDatabaseTrait;
142+
143+
public function testItRuns(): void
144+
{
145+
$client = static::createClient();
146+
147+
// Create a user (it must be an instance of UserInterface)
148+
$user = new User;
149+
$user->setEmail("[email protected]")
150+
->setPassword("password")
151+
->setRoles(['ROLE_MANAGER', 'ROLE_AUTHOR']);
152+
153+
// You get this from WithDatabaseTrait
154+
$this->getManager()->persist($user);
155+
$this->getManager()->flush();
156+
157+
// Then you can authenticate with this user
158+
$this->authenticate($client, $user, "my_firewall_name");
159+
$client->request('GET', '/protected/route');
160+
161+
// You can also override roles :
162+
$this->authenticate($client, $user, "my_firewall_name", ['ROLE_MODERATOR', 'ROLE_ADMIN']);
120163
$client->request('GET', '/admin/foo');
121164
}
122165
}

0 commit comments

Comments
 (0)