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

francoboy7's avatar

Laravel NOVA Testing with phpunit

Hi everyone,

I'm facing a weird issue when testing nova feature/unit

/** @test **/  
public function super_admin_has_ui_access()  
{ 
  $this->user->assignRole('super administrator');  
  $response = $this->get('/nova-api/users/1');  
  $response->assertStatus(200);  
}

this test fails because the page status is 403 (Forbidden)

However if I add

   $this->withoutMiddleware();  

Then the test suceeds. I'd like to know why I should remvoe the middleware for my tests as I thought testing should include all middleware to see if anything breaks ?

Also I think I ran make:auth in the past before installing Nova, could that be conflicting ?

Thank you

Also my SetUp function is the following in case you're wondering

public function setUp(): void  
{  
  parent::setUp();  
  if (!static::$setUpHasRunOnce) {  
      Artisan::call('migrate:fresh');  
      Artisan::call(  
      'db:seed', ['--class' => 'RolesTableSeeder']  
     );  
     static::$setUpHasRunOnce = true;  
 }  
 $this->user = factory(\App\User::class)->create();  
 $this->actingAs($this->user);  
}
0 likes
3 replies
bobbybouwmann's avatar

So the problem here is that you create a regular user, but not a "nova" user. You're logged in as this person, but it seems that it doesn't have access to nova itself, therefor you get the 403.

So are you sure the check in nova for who has access to nova itself is matching with the roles you assign this specific user?

The reason why it works without middleware is because there is no extra check anymore if your user can access the site or not. However all checks are disabled, so not an ideal situation!

1 like
francoboy7's avatar
francoboy7
OP
Best Answer
Level 7

Hey guys not sure if that will help but in NovaServiceProvider.php you got the gate function. I changed it to :

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

This is set to true to allow any user to access the dashboard (I then restrict resources access via the Resource file ) and it also allows testing nova (preventing 403 forbidden)

Explanation that I've gathered: On APP_ENV local, nova is always accessible, but when testing, APP_ENV is set to "testing", Nova then checks the gate restriction which would normally contain condition that checks for a user roles to make sure that user can access nova.

So either set your gate to true or comment out the following line in `phpunit.xml (unsure what are the impacts of doing so on other things though)

<server name="APP_ENV" value="testing"/>
3 likes
saiht's avatar

You literally saved my life. BIG THANKS!

Please or to participate in this conversation.