Laravel 5 unit testing Form and TokenMismatchException in Middleware

Posted by on December 26, 2014

While unit testing in Laravel 4 you were able to turn off filters including CSRF check in testing environment. However in the Laravel 5 CSRF check has been move into the middleware and I have not yet found the way to turn CSRF check off easily.

As TokenMismatchException will happen when testing controllers that are processing forms then I needed a hack to run the tests properly. I made a change to Illuminate\Foundation\Http\Middleware\VerifyCsrfToken . I added bypassing token check if environment is testing. You can do it also if you change the method handle to be like this

public function handle($request, Closure $next)
{
 if (env("APP_ENV")=="testing" || $this->isReading($request) || $this->tokensMatch($request))
 {
   return $this->addCookieToResponse($request, $next($request));
 }
 throw new TokenMismatchException;
}

Last modified on December 26, 2014

Categories: Laravel
2 Comments »

« | Home | »

2 Responses to “Laravel 5 unit testing Form and TokenMismatchException in Middleware”

  1. JtKese Says:

    Unfortunately, this solution will be overwritten every time you update Laravel with composer update.

    As an alternative, you can modify YourApp\Http\Middleware\VerifyCsrfToken to bypass checking the token before it reaches the stock middleware.

    public function handle($request, Closure $next)
    {
    if(env(‘APP_ENV’) == “testing”)
    {
    return $next($request);
    }

    return parent::handle($request, $next);
    }

  2. Martin Says:

    More correct solution would be not to modify token verification for tests, but ensure that tests work close to real life as much as possible, which means adding csrf token to request cookies or to each request as input value – just as you would do in real form.

Leave a Reply

*