php 在测试中使用空间权限没有权限

ki0zmccv  于 2023-01-01  发布在  PHP
关注(0)|答案(1)|浏览(279)

我正在使用角色和权限种子程序

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']));
    }
}

当我创建一个新雇主时,会创建一个用户,并为其分配雇主角色:

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');
        });
    }
}

现在,在雇主测试中,我想使用以下权限:

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());
    }
}

dd()items: []展示了什么是意料之外的。我错过了什么?雇主的用户有雇主角色,但它没有权限,但角色本身有权限。这里出了什么问题?

相关问题