TobiasS's avatar
Level 10

Test assertStatus(403) fails when $this->withoutExceptionHandling();

Hi!

I get an error, This action is unauthorized. when $this->withoutExceptionHandling(); is in the test. Any ideas why?

TEST:

test('Boss can view users on clinic /users', function() {
 
    $this->withoutExceptionHandling();

    actingAs($this->boss)->get('/users')->assertOk();
    actingAs($this->user)->get('/users')->assertStatus(403);
    actingAs($this->superadmin)->get('/users')->assertOk();
});

If I comment out the $this->withoutExceptionHandling(); the test passes.

ERROR MESSAGE

 • Tests\Feature\CreateUserTest > Boss can view users on clinic /users
   Illuminate\Auth\Access\AuthorizationException 

  This action is unauthorized.

  at vendor/laravel/framework/src/Illuminate/Auth/Access/Response.php:119
    115▕      */
    116▕     public function authorize()
    117▕     {
    118▕         if ($this->denied()) {
  ➜ 119▕             throw (new AuthorizationException($this->message(), $this->code()))
    120▕                         ->setResponse($this);
    121▕         }
    122▕ 
    123▕         return $this;

Thanks in advance!

0 likes
5 replies
tykus's avatar

An AuthorizationException is thrown, and then handled by the framework whenever you comment out the line. If you uncomment the line, the exception is thrown but is unhandled, so bubbles all the way up.

TobiasS's avatar
Level 10

I assume that it is right that an exception is thrown. User is not authorized. How do I assert in the test that the user is not authorized so that the test passes?

TobiasS's avatar
Level 10

Thx! Works perfectly fine.

Code in PEST


test('User  can not  view users on clinic /users', function() {
  $this->withoutExceptionHandling();
  actingAs($this->user)->get('/users');
})->throws(Exception::class, 'This action is unauthorized.');
tykus's avatar

Where is the value in expecting an Exception class; can you not make sure it is an AuthorizationException?

Please or to participate in this conversation.