gianlupu's avatar

Problem with HTTP headers in test

Hi guys, I'm facing a problem with some application tests. I'm using Laravel 5.7.

I have a test like this one

$response = $this->withHeaders([
    'X-App-Version' => 2,
    'X-App-Token' => '<token>',
])->json('POST', '/api/register', [
    <params>
]);

$response->assertStatus(200)
    ->assertJsonFragment([
        'status_code' => 0,
    ]);

Also I have a RouteServiceProvider where I load the proper routes file based on HTTP header provided

protected function mapApiRoutes()
{
    info(request()->headers); // In test is always empty

    $version = request()->header('X-App-Version', 1);

    switch ($version) {
            case 1:
                Route::prefix('api')
                    ->middleware('api')
                    ->namespace('App\V1\Controllers\API')
                    ->group(base_path('routes/api_v1.php'));

                break;
            case 2:
                Route::prefix('api')
                    ->middleware('api')
                    ->namespace('App\Controllers\API')
                    ->group(base_path('routes/api_v2.php'));

                break;
            default:
        }
}

Now the problem is that (only while testing) the request headers are not present in mapApiRoutes of ServiceProvider, so it will always load the v1 route file.

After some research I found that the RouteServiceProvider is loaded once on application tests start and is in common between all tests, so it doesn't have any request headers/parameters.

How can I pass request data to RouteServiceProvider while testing? Maybe I've used the wrong approach loading route file based on request headers in RouteServiceProvider.. any suggestion?

Thanks

0 likes
1 reply
D9705996's avatar

Not sure about the testing header part but why not put the version in your request URL? in /routes/api.php

Route::prefix('v1')->group(function () {
    //v1 routes
});

Route::prefix('v2')->group(function () {
    //v2 routes
});

Then in your tests (you could have v1, v2 folders, etc)

$this->json('POST', '/api/v1/register', $data)
    ->assertStatus(200)
    ->assertJsonFragment([
            'status_code' => 0,
        ]);

Please or to participate in this conversation.