Setting roles through rolify in FactoryBot definition

前端 未结 1 1659
悲&欢浪女
悲&欢浪女 2020-12-25 10:58

I am using devise, rolify and cancan. I\'m also using RSpec with FactoryBot for testing. Right now I\'m working on some tests and I want to define users with different roles

相关标签:
1条回答
  • 2020-12-25 11:42

    I would rather use FactoryBot's after(:create) callback to create roles (also see this issue for Rolify).

    Furthermore the method has_role? is used to check if a user has a specific role, to set a specific role you should use the add_role method.

    FactoryBot.define do
      factory :user do
        name 'Test User'
        email 'example@example.com'
        password 'please'
        password_confirmation 'please'
        # required if the Devise Confirmable module is used
        confirmed_at Time.now
    
        factory :admin do
            after(:create) {|user| user.add_role(:admin)}
        end
    
        factory :curator do
            after(:create) {|user| user.add_role(:curator)}
        end
    
        factory :super_admin do
            after(:create) {|user| user.add_role(:super_admin)}
        end
      end
    end
    

    Note: FactoryBot was previously called FactoryGirl

    0 讨论(0)
提交回复
热议问题