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

savins's avatar

Testing user authentication with roles - Laravel

Hi! I have an application with many user roles, so I've implemented this solution: https://laracasts.com/discuss/channels/laravel/version-8-redirects?page=1&replyId=639873

Everything work perfectly. However, I'm creating some features tests, and I want to test the login system. My problem resides that the test environment doesn't consider my class LoginResponse.php to redirect the user depending on its role, and it uses the HOME variable defined in RouteServiceProvider.

Does someone have the same problem as me?

Thanks!

0 likes
7 replies
tykus's avatar

the test environment doesn't consider my class LoginResponse.php to redirect the user depending on its role

How are you actually testing this?

savins's avatar

@tykus Thanks, I'm testing using this test feature:


    public function test_user_admin(){
        $user = User::factory()->create(['active'=>True]);
        $role_admin = Role::factory()->create(["name"=>"admin"]);

        $user->getRoles()->attach($role_admin);
        $response = $this->actingAs($user)->post("/login");

        $this->assertAuthenticated();
        $response->assertRedirect("dashboard");
    }

The problem is that I have another non-admin user type with another redirect dashboard that is defined in the LoginResponse. However, as I said above, the test does not consider the LoginResponse but only the HOME variable in the RouteServiceProvider.

tykus's avatar
tykus
Best Answer
Level 104

@savins this doesn't make sense:

$response = $this->actingAs($user)->post("/login");

You are acting as the User (i.e. authenticated already); and, you are attempting to sign in without credentials!

public function test_user_admin(){
    $user = User::factory()->create(['active'=>true]);
    $role_admin = Role::factory()->create(["name"=>"admin"]);
    $user->getRoles()->attach($role_admin);

    $response = $this->post("/login", [
        'email' => $user->email,
        'password' => 'secret', // this is the default Factory password!
    ]);

    $this->assertAuthenticated();
    $response->assertRedirect("dashboard");
}
1 like
savins's avatar

@tykus Oh! Thank you so much!! It worked perfectly! I thought "actingAs" was having the same role than "['email'=>.... 'secret',])";

Sorry for my (rookie) mistake I guess.

ousid's avatar

Which Auth scaffolding are you using? Meaning, are you implementing custom solution for login/roles system, or you are implementing a quick solution (e.g. spatie permissions/jetstream...)?

1 like

Please or to participate in this conversation.