Question: How to Disable Selected Middleware in Laravel Tests

Question

How to Disable Selected Middleware in Laravel Tests

Answers 1
Added at 2015-12-18 14:12
Tags
Question

So it is common that errors from Authentication and CSRF arise when running phpunit.

So in the TestCase we use:

use WithoutMiddleware;

The problem with this is that when forms fail, it usually comes back with a Flash Message and Old Input. We have disabled all middleware so we have no access to Input::old('username'); or the flash message.

Furthermore our tests of this failed form post returns:

Caused by
exception 'RuntimeException' with message 'Session store not set on request.

Is there a way to enable the Session Middleware and disable everything else.

Answers to

How to Disable Selected Middleware in Laravel Tests

nr: #1 dodano: 2015-12-18 15:12

The best way I have found to do this isn't by using the WithoutMiddleware trait but by modifying the middleware you want to disable. For example, if you want to disable the VerifyCsrfToken middleware functionality in your tests you can do the following.

Inside app/Http/Middleware/VerifyCsrfToken.php, add a handle method that checks the APP_ENV for testing.

public function handle($request, Closure $next)
{
    if (env('APP_ENV') === 'testing') {
        return $next($request);
    }

    if ($this->isReading($request) || $this->shouldPassThrough($request) || $this->tokensMatch($request)) {
        return $this->addCookieToResponse($request, $next($request));
    }

    throw new TokenMismatchException;
}

This will override the handle method inside of Illuminate\Foundation\Http\Middleware\VerifyCsrfToken, disabling the functionality entirely.

Source Show
◀ Wstecz