Ezrab_'s avatar

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.

0 likes
4 replies
Tray2's avatar

What does your login method look like?

tykus's avatar
tykus
Best Answer
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
Ezrab_'s avatar

You're right! Why is the error message inside the email array?

tykus's avatar

Why is the error message inside the email array?

Because that is how Validation error messages are returned by Laravel - a single input can have many validation rules, and multiple rules might fail in a given Request.

Please or to participate in this conversation.