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

osama_abdullah's avatar

policies unit tests doesn't work in laravel nova

when I want to test policies using PHPUnit it does not work as expected it works based on gate method in novaServiceProvider

protected function gate()
{
	Gate::define('viewNova', function () {
		return true;
	});
}

it only hits this method all policies are ignored, it seems that when using API this method override all policies,

however, when using web all policies are working as expected and it doesn't seem to hit this method at all

how to make policies work as expected in PHPUnit testing

0 likes
3 replies
bugsysha's avatar
bugsysha
Best Answer
Level 61

If you have a policy like following

class UserPolicy
{
	public function create(User $user): bool
	{
		return $user->isAdmin();
	}
}

Then just test it

public function test_admin_can_create_users(): void
{
	$admin = factory(User::class)->states('admin')->create();
	$this->assertTrue((new UserPolicy)->create($admin));
}

public function test_user_can_not_create_users(): void
{
	$user = factory(User::class)->create();
	$this->assertFlase((new UserPolicy)->create($user));
}
1 like
osama_abdullah's avatar

@bugsysha can't I do, because it's possible with laravel and I used to do that until now

public function test_admin_can_create_users(): void
{
	$admin = factory(User::class)->states('admin')->create();
	$this->assertStatus(201)->assertSee($admin->name);
}

???!!!

Please or to participate in this conversation.