Make sure user is admin
public function admin_can_create_a_branch(): void
{
$this->assertTrue($this->user->isAdmin());
}
what the logs say? and why 500 error instead of 403?
Hello,
I have a route to store a new model, this route is only accessible to admin users.
With Laravel 11.
class BranchTest extends TestCase
{
use RefreshDatabase;
public User $user;
public function setUp(): void
{
parent::setUp();
$this->user = User::create([
'name' => 'Vincent',
'email' => '[email protected]',
'password' => 'ksdlfgjsldfkg',
'admin' => true,
]);
}
/** @test */
public function admin_can_create_a_branch(): void
{
$response = $this->actingAs($this->user)->postJson('/api/branches', [
'name' => 'Ma super branche',
]);
$response->assertCreated();
$response->assertDatabaseHas('branches', [
'name' => 'Ma super branche',
]);
}
}
It returns a 500 error because the policy doesn't work.
public function create(User $user): bool
{
return $user->isAdmin();
}
And the controller checks for authorization via Gate::authorize('create', Branch::class);.
It works fine when I login and store a new branch, but the test fails.
Can you help me understand why ?
Thanks for your help.
V
@vincent15000 Chain withoutExceptionHandling to see the actual error being thrown:
$this
->actingAs($this->user)
->withoutExceptionHandling()
->postJson('/api/branches', [
'name' => 'Ma super branche',
])
->assertValid()
->assertCreated();
$this->assertDatabaseHas('branches', [
'name' => 'Ma super branche',
]);
Also, if you’re testing JSON responses and this is related to your earlier Sanctum question, then you should be specifying the guard when authenticating the user:
$this->actingAs($user, 'api')
Please or to participate in this conversation.