2012-04-12 77 views
3

行,所以我想測試我們需要一個管理員用戶的特點和我試圖以管理員身份登錄,但爲了做到這一點,我需要有一個管理員用戶如何使用Factory Girl創建管理員角色?

這裏是我的代碼

let(:user) { FactoryGirl.create(:user) } 
    let(:admin_role) { FactoryGirl.create(:role) } 

FactoryGirl.define do 
    factory :user do 
    first_name "John" 
    last_name "Doe" 
    email "[email protected]" 
    end 

    factory :role do 
    name "Admin" 
    end 
end 

我如何連接這些我想user.roles << user_role,但得到這個錯誤

/Users/matt/Sites/application/spec/controllers/directory_controller_spec.rb:16:in `block (3 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x007fa550890d80> (NameError) 

這裏是我的模型

class User < ActiveRecord::Base 
    has_many :roles, :through => :role_users 
    has_many :role_users 
    ... 

class Role < ActiveRecord::Base 
    has_many :users, :through => :role_users 
    has_many :role_users 
    ... 

class RoleUser < ActiveRecord::Base 
    belongs_to :role 
    belongs_to :user 
end 

回答

7
FactoryGirl.define do 
    factory :user do 
    first_name "John" 
    last_name "Doe" 
    email "[email protected]" 
    end 

    factory :admin_user, :parent => :user do 
    roles  { [ FactoryGirl.create(:admin_role) ] } 
    end 

    factory :role do 
    name  { "Role_#{rand(9999)}" } 
    end 

    factory :admin_role, :parent => :role do 
    name "Admin" 
    end 
end 
+0

你會如何使用這個在描述 – Trace 2012-04-12 21:25:32

+0

您是否正在尋找的anwser FactoryGirl.create(:admin_user) – 2012-04-13 14:01:58

+0

我試過了,並獲得和錯誤....我會貼現在 – Trace 2012-04-13 14:14:15

0

解決

Factory.sequence(:email) {|n| "person#{n}@example.com" } 

Factory.define :role do |r| 
    r.name {"Admin"} 
end 

Factory.define :role_user do |ru| 
    ru.association(:role) 
    ru.association(:user) 
end 

Factory.define :user do |u| 
    u.first_name {"matt"} 
    u.last_name {"jones"} 
    u.email {Factory.next(:email)} 
end 

,並用它像

let(:role_user) { FactoryGirl.create(:role_user) } 
    before { sign_in(role_user) } 
0

我有完全相同的問題,用類似的代碼:

describe "..." do 
    let(:user) { create :user } 
    let(:manager) { create :manager_role } 
    user.roles << manager 

    it "should ...." do 
    # etc. 
    end 

end 

# run rspec... 
# => `block (2 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x000001016a2dc0> (NameError) 

當我移動user.roles << manager代碼進入before(:each)塊,錯誤消失ARED。因此,像:

describe "..." do 
    let(:user) { create :user } 
    let(:manager) { create :manager_role } 

    before(:each) do 
    user.roles << manager 
    end 

    it "should ...." do 
    # etc. 
    end 

end 

這節省了您的工廠指定role <-> user協會的痛苦。

我不是如何RSpec的和factory_girl工作不夠熟悉,理解你爲什麼打電話let(:user) { create :user },但把它變成一個before(:each)塊或成個人it "should ... " do塊應該做的伎倆後不能有像user.roles << role代碼。

相關問題