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

chlab's avatar
Level 1

routes not being read in unit tests

Hi. I'm trying to write a unit test for an API controller action. I'm using Spark on Laravel 5.2.

My api.php file looks something like:

Route::group([
    'prefix' => 'api',
    'middleware' => 'cors',
], function () {
    Route::post('employees/{employee}/appointments', 'AppointmentController@store');
});

And in the unit test (it's extending TestCase):

$response = $this->action('POST', 'AppointmentController@store', $data);

I'm getting a Not Found back from the server. I have also tried using a named route and using the route() helper to build an URL to it.

I did a a lot of googling and some debugging. There seems to be a common problem with having require_once in the RouteServiceProvider. Mine looks like:

protected function mapApiRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace,
        ], function ($router) {
            require app_path('Http/api.php');
        });
    }

But - it doesn't seem to be called, neither is the map() method in the same class. Only the boot() method is called.

Any help on this?

0 likes
2 replies
Cronix's avatar
Cronix
Best Answer
Level 67

@chlab You might be able to find out by examining the official spark tests, which can be found here:

https://github.com/laravel/spark-tests/tree/3.0/tests

It looks like they have tests for v3, and v6 (change the branch). Other than that I haven't done tests with spark so don't know what else to suggest since I haven't tried it, but hopefully it will point you in the right direction.

Like here https://github.com/laravel/spark-tests/blob/6.0/tests/RegistrationTest.php

    public function test_users_can_register()
    {
        $this->json('POST', '/register', [
            'team' => 'Laravel',
            'name' => 'Taylor Otwell',
            'email' => '[email protected]',
            'password' => 'secret',
            'password_confirmation' => 'secret',
            'terms' => true,
        ])->assertSuccessful();
        $this->assertDatabaseHas('users', [
            'email' => '[email protected]',
        ]);
        $this->assertTrue(
            User::where('email', '[email protected]')->first()->onGenericTrial()
        );
    }

Edit: it looks like they are using the actual url's and not route()'s.

chlab's avatar
Level 1

Thanks @Cronix

I just tried that and I'm still getting 404 Not Found :/

var_dump($this->call('POST', '/the/path'));

Please or to participate in this conversation.