What does your login method look like?
Jun 22, 2021
4
Level 1
Laravel unit test doesn't validate correctly
I'm using laravel fortify's default login and register functionalities to test the login route in my application. For some reason though my test is failing.
{
"message": "The given data was invalid."
"errors": {
"email": [
0 => "These credentials do not match our records."
]
}
}
My code is:
public function test_user_can_login()
{
$user = User::factory()
->create();
$response = $this
->assertGuest()
->postJson('/login', [
'email' => $user->email,
'password' => $user->password
]);
$response->assertOk();
$this->assertAuthenticated();
}
I'm also using the RefreshDatabase trait in my class.
I would assume that creating the user that way also stores it in the database, however just to be sure I also already tried to do $user->save(); to make sure it actually gets saved to the database, yet still I receive this error.
Level 104
The problem is... you are attempting to use the hashed password to authenticate the user. $user->password is not the User's password!
public function test_user_can_login()
{
$user = User::factory()
->create(['password' => bcrypt('secret')]);
$response = $this
->assertGuest()
->postJson('/login', [
'email' => $user->email,
'password' => 'secret'
]);
$response->assertOk();
$this->assertAuthenticated();
}
1 like
Please or to participate in this conversation.