Home > Net >  Using Spatie Permissions in Test doesn't have permissions
Using Spatie Permissions in Test doesn't have permissions

Time:12-31

I am using a RolesAndPermissionsSeeder:

class RolesAndPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $permissions = [
            'employers.index',
            'employers.show',
            'employers.create',
            'employers.edit',
            'employers.destroy',
        ];

        foreach ($permissions as $permission) {
            Permission::create(['name' => $permission]);
        }

        $role = Role::create(['name' => "Employer"]);
        $role->givePermissionTo(Permission::all()->except(['employers.index', 'employers.destroy']));
    }
}

When I create a new employer, a user get's created with it and it gets assigned a Employer role:

class Employer extends Model
{
    use HasFactory;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    protected static function booted()
    {
        static::created(function ($employer) {
            $employer->user->assignRole('Employer');
        });
    }
}

Now in the EmployerTest I want to use the permissions:

class EmployerTest extends TestCase
{

    use RefreshDatabase;
    use WithFaker;

    public function setUp(): void
    {
        parent::setUp();

        $this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
        $this->seed(RolesAndPermissionsSeeder::class);
    }

    public function test_permission()
    {
        $employer = \App\Models\Employer::factory()->create();

        dump(Role::all()); // <-- shows all roles correctly
        dump(Permission::all()); <-- shows all permissions correctly
        dump(Role::where('name', 'Employer')->first()->permissions->pluck('name')->toArray()); // <-- shows the assigned permissions
        dump($employer->user->hasRole('Employer')); // <-- shows true
        dd($employer->user->getPermissionNames());
    }
}

The dd() shows items: [] what is unexpected. What am I missing? The Employer's user has the Role Employer but it does not have the permissions, but the role itself has it. What's wrong here?

CodePudding user response:

I think what you are missing is $employer->user->getAllPermissions() according to the documentation : https://spatie.be/docs/laravel-permission/v5/basic-usage/role-permissions

  • Related