Dynamic route url change is not reflecting in laravel package

532 Views Asked by At

I am creating a package which gives a config file to customize the route url which it will add, I can see config file values in the controller, but same config('app_settings.url') is coming as null in pakacge/src/routes/web.php

Route::get(config('app_settings.url'), 'SomeController')

my tests are also giving 404 and app_settings config change is not getting picked by route.

function it_can_change_route_url_by_config() {
  // this should be default url
  $this->get('settings')
    ->assertStatus(200);

  // change the route url
  config()->set('app_settings.url', '/app_settings');

  $this->get('app_settings')
    ->assertStatus(200);

  $this->get('settings')
    ->assertStatus(400);
}

app_setting.php

return [
    'url' => 'settings',
    'middleware' => []
];

It works when I use this package, but tests fail.

Please help How I can give the option to change the route url from config.

1

There are 1 best solutions below

1
On

To be honest I think it's impossible to make such test. I've tried using some "hacky" solutions but also failed.

The problem is, when you start such test, all routes are already loaded, so changing value in config doesn't affect current routes.

EDIT

As alternative solution, to make it a bit testable, in config I would use:

<?php

return [
    'url' => env('APP_SETTING_URL', 'settings'),
    'middleware' => []
];

Then in phpunit.xml you can set:

<env name="APP_SETTING_URL" value="dummy-url"/>

As you see I set here completely dummy url to make sure this custom url will be later used and then test could look like this:

/** @test */
function it_works_fine_with_custom_url() 
{
    $this->get('dummy-url')
        ->assertStatus(200);

    $this->get('settings')
        ->assertStatus(404);
}

Probably it doesn't test everything but it's hard to believe that someone would use dummy-url in routing, and using custom env in phpunit.xml give you some sort of confidence only custom url is working fine;