netdjw's avatar
Level 15

Route list contain route but in test I get 404 error

I have this code in my web.php:

Route::middleware('auth:sanctum')->group(function () {
    Route::prefix('webshop')->group(function () {
        Route::get('basket', [BasketController::class, 'show'])->name(RouteName::BASKET_SHOW);
    });
});

In the controller:

    public function show(PublicViewBasketRequest $request)
    {
        // ...
    }

And in my test file:

    /** @test */
    public function shouldShowAsAuthorizedUser(): void
    {
        // ...
        $this->get(action([$this->controller, 'show']))
            ->assertOk();
        // ...
    }

When I run php artisan route:list | grep basket command I see this line in the result:

  GET|HEAD        webshop/basket basket.show › Domain\Webshop\Http\Controller…
  PUT             webshop/basket basket.update › Domain\Webshop\Http\Controll…

And when I run the test I get this result:

1) Domain\Webshop\Tests\Basket\BasketControllerRegisteredMemberTest::shouldShowAsAuthorizedUser
Expected response status code [200] but received 404.
Failed asserting that 200 is identical to 404.

So the route actually exists, but the test call don't see it.

I found out if I use the route like this:

Route::get('my/basket', [BasketController::class, 'show'])->name(RouteName::BASKET_SHOW);

...then the test is pass. (The modification is the my/ part of the route. The my word is can be any word. The slash is the point with two words/strings.)

So the question is why don't working the route without my/ part? What is the hidden Laravel magic behind this issue?

0 likes
3 replies
fylzero's avatar

@netdjw Are you sure action([$this->controller, 'show']) is acting correctly in the test? What happens if you just check $this->get('/webshop/basket')->assertOk();?

Looks like the route name may be wrong there. Should be basket.show not just show, right? This may be my ignorance of how the action helper works - never really reached for that. Just what I'd suspect at a glance. Apologies in advance if this winds up being a useless suggestion.

netdjw's avatar
Level 15

@fylzero the action is acting correctly, we use this syntax everywhere in our app, and it gives back the proper route. So unfortunatelly, your answer is not a solution for our issue.

fylzero's avatar

@netdjw I was assuming the question based on the title. Didn't even fully read the actual question - last line. Not sure what could be causing this. I ran into something similar trying to use /vendor as an endpoint. Not sure if basket would be a magic word issue. If I have time, I'll try this later and let you know if I hit the same problem.

1 like

Please or to participate in this conversation.