Alexandru Negura
Alexandru Negura

Reputation: 1

Unit Testing authenticated user in Laravel

I am developing an app and now I need to do some testing. Everything in the app is based on authenticated user so this is the first test that I need to do. I have a google captcha in the form but I modified the .env file so that will not be required. This is my feature test.

public function test_users_can_authenticate()
{
     $user = User::factory()->create();

     $response = $this->get('/login', [
         '_token' => csrf_token(),
         'email' => $user->email,
         'password' => 'secret',
         'g-recaptcha-response' => ''
     ]);
        
     $this->assertAuthenticated();
     $response->assertRedirect(RouteServiceProvider::HOME);
}

The test is failing on this line $this->assertAuthenticated(); saying that The user is not authenticated. Failed asserting that false is true. I did not now what can I do to make it work. I tried php artisan config:clear before php artisan test, not working. I uncomment the lines in phpunit.xml

<!-- <server name="DB_CONNECTION" value="mysql"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->

but still with no result. Working with Laravel 8.x. What can I do to make this work? Thanks.

Upvotes: 0

Views: 1842

Answers (1)

so2emma
so2emma

Reputation: 11

The first thing to do is for you to create a protected function in your TestCase.php like this.

protected function user()
{
    return (User::factory()->create());
}

After you do this, you can call it in the test of your application.

public function test_users_can_authenticate()
{
$this->actingAs($this->user()
->assertStatus(302);
}

Upvotes: 1

Related Questions