简体   繁体   中英

How does one load gate defines when testing a Laravel application?

I'm writing tests for a Laravel application. In my AuthServiceProvider->boot() , I define a number of user abilities with $gate->define() based on a permissions table in my database.

Basically this:

 foreach ($this->getPermissions() as $permission) {
            $gate->define($permission->name, function ($user) use ($permission) {
                return $user->hasPermission($permission->name);
            });
        }

In my tests I'm creating permissions on the fly, but the AuthServiceProvider has already booted up, which means I can't verify user permissions with @can , Gate , etc.

Is there a proper way to deal with this issue?

public function boot(GateContract $gate)
{
    parent::registerPolicies($gate);

    $gate->before(function($user, $ability) use ($gate){
        return $user->hasPermission($ability);
    });
}

I haven't extensively tested this, but it seems to work from my quick tests.

I know I'm a bit late for the party on this one, but still - I just had the same problem myself and hence this question doesn't have a comprehensive answer, here is my solution for the same issue (in Laravel 5.3):

I've got this in my app\\Providers\\AuthServiceProvider :

/**
 * Register any authentication / authorization services.
 *
 * @param Gate $gate
 */
public function boot(Gate $gate)
{
    $this->registerPolicies();

    if (!app()->runningInConsole()) {
        $this->definePermissions($gate);
    }
}

/**
 * @param Gate $gate
 */
private function definePermissions(Gate $gate)
{
    $permissions = Permission::with('roles')->get();

    foreach($permissions as $permission) {
        $gate->define($permission->key, function($user) use ($permission) {
            return $user->hasRole($permission->roles);
        });
    }
}

This takes care of the normal application flow when not testing and disables the premature policy registration when testing.

In my tests/TestCase.php file I have the following methods defined (note that Gate points to Illuminate\\Contracts\\Auth\\Access\\Gate ):

/**
 * Logs a user in with specified permission(s).
 *
 * @param $permissions
 * @return mixed|null
 */
public function loginWithPermission($permissions)
{
    $user = $this->userWithPermissions($permissions);

    $this->definePermissions();

    $this->actingAs($user);

    return $user;
}

/**
 * Create user with permissions.
 *
 * @param $permissions
 * @param null $user
 * @return mixed|null
 */
private function userWithPermissions($permissions, $user = null)
{
    if(is_string($permissions)) {
        $permission = factory(Permission::class)->create(['key'=>$permissions, 'label'=>ucwords(str_replace('_', ' ', $permissions))]);

        if (!$user) {
            $role = factory(Role::class)->create(['key'=>'role', 'label'=>'Site Role']);

            $user = factory(User::class)->create();
            $user->assignRole($role);
        } else {
            $role = $user->roles->first();
        }

        $role->givePermissionTo($permission);
    } else {
        foreach($permissions as $permission) {
            $user = $this->userWithPermissions($permission, $user);
        }
    }

    return $user;
}

/**
 * Registers defined permissions.
 */
private function definePermissions()
{
    $gate = $this->app->make(Gate::class);
    $permissions = Permission::with('roles')->get();

    foreach($permissions as $permission) {
        $gate->define($permission->key, function($user) use ($permission) {
            return $user->hasRole($permission->roles);
        });
    }
}

This enables me to use this in tests in multiple ways. Consider the use cases in my tests/integration/PermissionsTest.php file:

/** @test */
public function resource_is_only_visible_for_those_with_view_permission()
{
    $this->loginWithPermission('view_users');
    $this->visit(route('dashboard'))->seeLink('Users', route('users.index'));
    $this->visit(route('users.index'))->assertResponseOk();

    $this->actingAs(factory(User::class)->create());
    $this->visit(route('dashboard'))->dontSeeLink('Users', route('users.index'));
    $this->get(route('users.index'))->assertResponseStatus(403);
}

/** @test */
public function resource_action_is_only_visible_for_those_with_relevant_permissions()
{
    $this->loginWithPermission(['view_users', 'edit_users']);
    $this->visit(route('users.index'))->seeLink('Edit', route('users.edit', User::first()->id));

    $this->loginWithPermission('view_users');
    $this->visit(route('users.index'))->dontSeeLink('Edit', route('users.edit', User::first()->id));
}

This works just fine in all my tests. I hope it helps.

You could do something like this inside AuthServiceProvider

First import the necessary packages

use Illuminate\Auth\Access\Gate;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

and then add this boot() method

public function boot(GateContract $gate)
{
    parent::registerPolicies($gate);

    $gate->define('update-post', function ($user, $post, $isModerator) {
        // check if user id equals post user id or whatever
        if ($user->id === $post->user->id) {
            return true;
        }

        // you can define multiple ifs
        if ($user->id === $category->user_id) {
            return true;
        }

        if ($isModerator) {
            return true;
        }

        return false;
    });

    // you can also define multiple gates
    $gate->define('update-sub', function($user, $subreddit) {
        if($user->id === $subreddit->user->id) {
            return true;
        }

        return false;
    });

And then in your controller you could do something like this

if (Gate::denies('update-post', [$post, $isModerator])) {
    // do something
}

I'm not sure what the "proper" way (if there is one) to define a gate for testing. I couldn't find an answer for this after looking at the documentation and searching, but this seems to work in a pinch in Laravel 5.7:

Defining a gate in a model factory state :

$factory->state(App\User::class, 'employee', function () {
    Gate::define('employee', function ($user) {
        return true;
    });
    return [];
});

This test function will have both the 'employee' and the 'admin' gate applied since we are using the 'employee' state when creating the user:

/** @test */
public function an_admin_user_can_view_the_admin_page()
{
    $user = factory('App\User')->state('employee')->make();
    $this->actingAs($user);

    Gate::define('admin', function ($user) {
        return true;
    });

    $this->get('/admin')
        ->assertOk();
}

I know this is a really old question, but it was the top result in a search and hopefully can help someone.

Don't forget to use the Gate facade:

use Illuminate\Support\Facades\Gate;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM