emabusi's avatar

Defining and using named route in laravel unit test (phpunit)

I have created a helper method the uses laravel route to reformat the result returned from laravel URL::route($routeName) as below


    public static function route($routeName)
        {
            $path = URL::route($routeName);
    
            if(env('APP_SECURE', true)){
                $path = str_replace('http','https',$path);
            }
    
            return $path;
        }

I am creating a unit test for the method as below


    public function can_get_path_from_route_name_and_apply_app_secure_attribute()
    {
        $path = '/testing';

        Route::get($path, function () {

            return Helper::route('test_route');

        })->name('test_route');
        
        $response = $this->get($path);

        $generatedPath = $response->getContent();
        
        var_dump($generatedPath);

        
    }

I get the error when trying to use the methos, a laravel HTML error is return with exception message "Route [test_route] not defined."

0 likes
1 reply
danielsdeboer's avatar

So this doesn't work:

Route::any('test-route')->name('test-route');

But this does:

Route::any('test-route', ['as' => 'test-route']);

And it needs to be called in the setUp() method, not in the test itself:

protected function setUp () {
    parent::setUp();

    Route::any('test-route', ['as' => 'test-route'];
}

Please or to participate in this conversation.