Search code examples
laravellaravel-middlewarelaravel-testing

Laravel feature test using middleware


I'm trying to make a feature test for the start page of my Laravel application.

Route:

Route::domain('{subdominio}.'.env("APP_DOMAIN"))->middleware('mapNumserie')->group(function () {
    Route::get('/', 'FarmaciaController@show')->middleware('modomtofarmacia')->name('inicio');
})

For some reasons, I use a middleware mapNumserie where I map the subdomain aganist a serial number $idfarmacia in order to use it after in controller:

public function handle($request, Closure $next){
    try{
        $route = $request->route();
        $idfarmacia = \App\Farmacia::where('subdominio', $route->subdominio)->value('numserie');
        $route->setParameter('idFarmacia', $idfarmacia);
        $route->forgetParameter('subdominio');
    }
    catch (\Exception $e){
        abort(404);
    }
    return $next($request);
}

In my ModoMtoFarmacia middleware I just check that an app instance is not in maintenance mode or disabled:

public function handle(Request $request, Closure $next){
        $farmacia = \App\Farmacia::find($request->idFarmacia);
        if($farmacia->inactiva){
            abort(404);
        }
        if(!$farmacia->modomantenimiento){
            return $next($request);
        }
        else{
            return response()->view('errors.503')->setStatusCode(503);
        }
    }

In my controller symply get some data using this $idfarmacia and return a view:

public function show(Request $request, $idfarmacia) {
    $data = 
        //Query...
    if($data){
        return view('inicio', ['data' => $data]);
    }
    else{
        abort(404);
    }

}

With a very simple test method I hope to validate a 200 response :

public function test_example(){
    $response = $this->get('http://mysubdomain.domain.prj');
    $response->assertStatus(200);
}

But when I run the test I get:

Expected response status code [200] but received 404.

The used URL works correctly in web environment, but the test fails. Where am I wrong?


Solution

  • Finally a found the problem in my phpunit.xml settings, which caused an error in the first query (also in any other), in this case the one found in the MapNumserie middleware:

     $idfarmacia = \App\Farmacia::where('subdominio', $route->subdominio)->value('numserie');
    

    I had to set up properly the values of DB_DATABASE and DB_CONNECTION