#Test fails to retrieve user when using factory, but works using Mode::create();

14 messages · Page 1 of 1 (latest)

deft zephyr
#

I'm trying to test my authentication routes, but for some reason I can't use a factory to create a user and login. When I use the factory, it returns saying that user does not exist. When I use the Model::create it works fine.

I'm using the same test as one of my other projects, the only difference is that I'm using just username/password instead of email/password like the default Laravel User model. So I'm not really sure if I forgot to set something or it just doesn't want to work for me.

public function test_user_can_login(): void
{
  $user = User::factory()->create();
  //$user = User::create(['name' => 'test', 'password' => 'password']);

  $this->followingRedirects()
    ->post('/login', [
      'name' => $user->name,
      'password' => 'password'
    ]);

  $this->assertAuthenticatedAs $user , 'web');
}```
dull depot
#

Does your user model have the HasFactory trait in it @deft zephyr?

deft zephyr
#

Yep

#

It creates the User fine. I can view the user after it's created but when I try to login the user, it can't find the user.

viral stag
#

But when you use the factory...what's your default definition for name and password? Are you sure you're using the right combination? When you create the user manually, I see you pass a plain text password. Is this because you use a mutator to hash the password when it's set?

deft zephyr
#

I'm using the default user factory Laravel provides minus the email fields. I did add a mutator to hash the password on the User model.

#

It was the mutator and the factory definition... Thanks lol I forgot to change the factory to be plain text instead of the hashed value.

viral stag
#

Eyy

#

(I use mutators to hash passwords as well, so your above instantly brought back memories of issues I've had in the past)

timid otter
#

For test speed, I'd suggest using a hardcoded bcrypt string in the factory

viral stag
#

@timid otter that doesn't work when we've done the above (choose to use Attribute mutator to set hashed passwords automatically for us)

timid otter
#

I see, I guess the speed is fine with the cost factor of 4 (set in phpunit.xml)

viral stag
#

I can pass a validated array directly to my user update and have no cares in the world.