There isn’t a user in the database
Testing loginform not working in featuretest?
Hi,
i'm trying to write a test that checks if i can authenticate with the correct user+pass when using my login form, and also check that i cannot login with missmatching user+pass. However i keep getting a failed test, saying i'm not authenticated even when user+pass is correct and it works as expected on the frontend.
AdminTest.php (Laravel 8, PHP 8.1)
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Tests\TestCase;
use App\User;
/**
* php artisan test --filter AdminTest
*/
class AdminTest extends TestCase
{
/**
* check if a user can login with correct credentials
*/
public function test_user_can_login_with_correct_credentials()
{
$email = config('app.siteadmin.email');
$password = 'hunter2';
$user = \App\User::where('email', '=', $email)->first();
//post email and password to signin page
$this->followingRedirects();
$response = $this->post(route('user.signin'), [
'email' => $email,
'password' => $password,
]);
$response->dumpSession();
$this->assertAuthenticatedAs($user);
}
}
The failes test output says that $user is null:
array:3 [
"_previous" => array:1 [
"url" => "http://127.0.0.1/login"
]
"_token" => "gQjZFrYe7VGMJmUtPWlDCkA9Yd1ywZLUettUOLzC"
"_flash" => array:2 [
"new" => []
"old" => []
]
]
FAIL Tests\Feature\AdminTest
⨯ user can login with correct credentials
---
• Tests\Feature\AdminTest > user can login with correct credentials
The current user is not authenticated.
Failed asserting that null is not null.
at \tests\Feature\AdminTest.php:74
70▕ 'email' => $email,
71▕ 'password' => $password,
72▕ ]);
73▕ $response->dumpSession();
➜ 74▕ $this->assertAuthenticatedAs($user);
75▕ }
76▕
77▕ /**
78▕ * check if a user can access the admin panel with correct credentials
1 \vendor\phpunit\phpunit\phpunit:98
PHPUnit\TextUI\Command::main()
Tests: 1 failed
Time: 0.21s
I checked all the variables, routes and urls and they are correct. However i assume the login fails because the hidden "_token" from the original login form is never set, and cannot be passed on to to route('user.signin'). I cannot find a working example of how to test my login form in the laravel documentation or online, for what seems to me should be a basic fuction...?! Had a look at vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php, but there seems to be nothing that explicitly handles "_token"...
What am i doing wrong, and what is the best way to test the login form here?
Please or to participate in this conversation.