php - Laravel 5.4 - integration testing role middleware fails


I'm trying to test some middleware that checks to see if a user hasx role with Laravel 5.4/PHPUnit. The role functionality works fine in the browser, but I can't seem to get my tests to pass (I get 403's as expected with someone without the required role) with the following code:

public function testSuperAdminRoleRoute()
    $admin = factory(User::class)->create();
    $adminRole = \HttpOz\Roles\Models\Role::whereSlug('super.admin')->first();


    $response = $this->actingAs($admin)

When Idd($admin->roles) I do indeed see the correct role, but I think I'm missing something maybe a limitation within Laravel/PHPUnit. I have previously tested this sort of functionality in my acceptance tests and had it work.

Any advice is much appreciated!




After talking to the package author (httoz), we believe it's due to a limitation of Laravel'sbe() oractingAs() methods. We're not really 100% sure as to why, but I believe sessions come into play, and PHPUnit uses an array as session storage, so I'm pushed towards that.

I tried to use$this->disableMiddleware(), but because I use the$error bag in my views (and that is set via middleware), my tests 500 because$errors isn't defined.

However, reading this proposed change in Laravel 5.5:

I copied the code from that push:

public function withoutMiddleware($middleware = null)
    if (is_null($middleware)) {
        $this->app->instance('middleware.disable', true);
        return $this;
    $nullMiddleware = new class {
        public function handle($request, $next)
            return $next($request);
    foreach ((array) $middleware as $abstract) {
        $this->app->instance($abstract, $nullMiddleware);
    return $this;

and set updated my$this->withoutMiddleware() calls to this:


and I get green again!

People are also looking for solutions to the problem: Creating a config file in PHP


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.