Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Testing roles: only Admin can access creating products

Premium
7:48

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

A
Artan ✓ Link copied!

Hello Povilas, In the company im currently working luckymedia, in TestCase.php we create a separate public function as follows:

 public function loginAs($admin = false)
    {
        $user = User::factory()->create(['admin' => $admin]);

        return $this->actingAs($user);
    }

, then when we want to be logged as an admin we test as follows:

$this
     ->loginAs(true)
     ->get(route('users.index'))
     ->assertStatus(200);

Is this the propper way to test, or can you suggest a better approach?

Thanks in advance

PK
Povilas Korop ✓ Link copied!

Yes, that's a perfectly fine approach, to avoid repeating the same thing in each test.

PP
Pouya Parsaei ✓ Link copied!

One of the clean code tips is to not defining flags as an argument for your functions. instead you should divide the login into multiple functions. By this way, you also won't violate SRP principle.

I suggest using factory states, like below. UserFactory:

class UserFactory extends Factory
{

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
            'is_admin' => false
        ];
    }

    public function admin()
    {
        return $this->state(function (array $attributes) {
            return [
                'is_admin' => true,
            ];
        });
    }
}

then using it like this:

User::factory()->admin()->create();