通过FactoryGirl定义中的rolify设置角色

时间:2012-09-12 03:55:42

标签: ruby-on-rails rspec devise factory-bot

我正在使用设计,rolify和cancan。我还使用rspec和FactoryGirl进行测试。现在我正在进行一些测试,我想为那些测试定义具有不同角色的用户。以下是我目前对如何使用FactoryGirl进行测试的猜测:

FactoryGirl.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
        self.has_role :admin
    end

    factory :curator do
        self.has_role :curator
    end

    factory :super_admin do
        self.has_role :super_admin
    end
  end
end

以下是我的一些测试,似乎没有正确写入: 要求' spec_helper'

describe "Pages" do
    subject { page }

    before do
        @newpage = FactoryGirl.create(:page)
        @newpage.save
    end

    context 'not logged in' do
        it_behaves_like 'not admin'
    end

    context 'logged in' do

        context 'as user' do
            before do
                @user = FactoryGirl.create(:user)
                sign_in @user
            end

            it_behaves_like 'not admin'
        end

        context 'as curator' do
            before do
                @curator = FactoryGirl.create(:curator)
                sign_in @curator
            end

            it_behaves_like 'not admin'
        end

        context 'as admin' do
            before do
                @admin = FactoryGirl.create(:admin)
                sign_in @admin
            end

            it_behaves_like 'admin'
        end

        context 'as super admin' do
            before do
                @super_admin = FactoryGirl.create(:super_admin)
                sign_in @super_admin
            end

            it_behaves_like 'admin'
        end
    end
end

当我运行规范时,这些是我的错误:

1) Pages logged in as admin behaves like admin can show page 
 Failure/Error: Unable to find matching line from backtrace
 NoMethodError:
   undefined method `has_role=' for #<User:0x007f883384d178>
 Shared Example Group: "admin" called from ./spec/requests/pages_spec.rb:41
 # ./spec/requests/pages_spec.rb:37:in `block (4 levels) in <top (required)>'

2) Pages logged in as curator behaves like not admin can show page 
 Failure/Error: Unable to find matching line from backtrace
 ArgumentError:
   Factory not registered: curator
 Shared Example Group: "not admin" called from ./spec/requests/pages_spec.rb:32
 # ./spec/requests/pages_spec.rb:28:in `block (4 levels) in <top (required)>'

3) Pages logged in as super admin behaves like admin can show page 
 Failure/Error: Unable to find matching line from backtrace
 ArgumentError:
   Factory not registered: super_admin
 Shared Example Group: "admin" called from ./spec/requests/pages_spec.rb:50
 # ./spec/requests/pages_spec.rb:46:in `block (4 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:59)

我宁愿使用FactoryGirls after(:create) callback来创建角色(另请参阅Rolify的this问题)。

此外,如果用户具有特定角色,方法has_role?用于检查设置您应使用{{1}的特定角色方法。

add_role