Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

christophrumpel's avatar

Testing Login with User Factory

Hey,

I am having troubles testing login with model factory. When I test it with email and pw from a given user, it works.

But when I try to test it with a new user (factory) it doesn't work. The user is not redirected to home. This is why I it is not working.

Cheers

// User factory
$factory->define(Famulous\Http\Repositories\Users\User::class, function ($faker) {
return [
    'email' => $faker->email,
    'firstname' => $faker->name,
    'password' => bcrypt(str_random(10)),
    'remember_token' => str_random(10),
];
});

// part from my test file
public function testLoginPage()
{
    $user = factory(User::class)->make([
        'group_id' => 1,
        'password' => bcrypt('test')
    ]);

    $this->visit('/login')
        ->submitForm('Login', [
           'email' => $user->email,
           'password' => 'test',
        ])->onPage('/home');
}
0 likes
3 replies
cbojer's avatar

So, it works if you do it in the browser, but not in your test?

If that is the case, are you sure that you are not accidentally double hashing your password or something like that? If you have a setPasswordAttribute on your User model that automatically hashes the password, then that could be the problem.

Otherwise, I'll need to know more in order to help you.

christophrumpel's avatar

Hey,

no it is working in my test too, when I hard code a user and pw from a user I know is in the db. This is working with the unhashed password and I guess I need to use the un-hashed pw for filling out the form in the test.

I dont have set any setPasswordAttribute =(

Cheers

justgiz's avatar

You want to use create() not make() so your user will be saved to the database. You'll also want to enable database transactions so the database is reset after the test.

Please or to participate in this conversation.