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

dguilmezian's avatar

My HTTP test ignores middleware

i have this test

public function testCanViewMonthlyReport(): void
{
    $account = $this->createFakeAccount();

    $order = Order::factory()->create([
        'account_id' => $account->id,
    ]);

    $salesUser = User::factory()->createOneQuietly(['role_id' => Role::ROLE_USER_SALES]);

    $this->actingAs($salesUser)
        ->get('/report/order-monthly-report/' . $order->id)
        ->assertForbidden();
}

this is my route

Route::group(['middleware' => ['auth', 'roles'], 'roles' => [Role::ROLE_USER_ADMIN, Role::ROLE_USER_ANALYST]], function () {
Route::get('/report/order-monthly-report/{orderId}', ['as' => 'report.order-monthly-report', 'uses' => 'ReportController@orderMonthlyReport']);
});

As a result, it should return a 403 Forbidden response. But when the test performs a GET request to that endpoint, it unexpectedly returns a 200 OK response instead of the expected 403. This is causing a false positive. What changes do I need to make to my test to fix this? The functionality works as expected when I manually navigate to the route in the browser, so the roles middleware is configured correctly.

I believe the issue is that the middleware isn't being loaded within the testing environment.

0 likes
3 replies
tisuchi's avatar

@dguilmezian You may try with withMiddleware().

For example-

public function testCanViewMonthlyReport(): void
{
    $account = $this->createFakeAccount();

    $order = Order::factory()->create([
        'account_id' => $account->id,
    ]);

    $salesUser = User::factory()->createOneQuietly(['role_id' => Role::ROLE_USER_SALES]);

    $this->withMiddleware() // Ensure middleware is enabled
        ->actingAs($salesUser)
        ->get('/report/order-monthly-report/' . $order->id)
        ->assertForbidden(); // Expect 403 response
}
dguilmezian's avatar

@tisuchi hi! i tried withMiddleware() and nothing. i tried passing the middlewares like this withMiddleware(['auth', 'roles']) and also nothing. :(

Talinon's avatar

@dguilmezian

The first thing I would do is confirm that you're hitting the correct endpoint.

ReportController:

public method orderMonthlyReport(Order $order) {
	dd('hit');
}

Then run your test. If you don't see that dumped, then you know the problem is with routing. Otherwise, I'd then move onto the middleware itself and do something similar. Drop another dd() within the middleware and confirm it's actually being invoked.

If the middleware is called, then review the middleware and see why it's not working. At this point, it's probably the way you're setting up the test. You didn't share your middleware, so there is no way for us to know, but perhaps there is something you're missing building up in your test.

Please or to participate in this conversation.