How to test Auth::once() in Laravel?

390 Views Asked by At

I'm using Auth:once() to authenticate users for a single request.

if (!Auth::once($this->only('email', 'password'))) {
    RateLimiter::hit($this->throttleKey());

    throw ValidationException::withMessages([
        'email' => __('auth.failed'),
    ]);
}

// we store the user + password for one request in the session
// so we can use it in the next request
$this->session()->put('email', $this->email);
$this->session()->put('password', $this->password);

But the test user is permanently authenticated, and assertGuest() is always false, not just for a single request. This is happening only in the test!

$user = User::factory()->create();

$response = $this->post('/api/login', [
    'email' => $user->email,
    'password' =>' password',
]);

$response = $this->get('/api/home');

$this->assertGuest();

I tested manually from Postman, and everything seems to be okay. So I think Laravel considers it a single request for the entire test.

0

There are 0 best solutions below