2016-05-01 28 views
0

相關的記錄,我有以下的工廠女孩​​創建用戶:Rails的工廠女孩​​:創建用戶,但與角色

FactoryGirl.define do 
factory :user do 
    first_name 'Colin' 
    last_name 'Ambler' 
    password 'dell13a1' 
    address_zip '60657' 

    trait :event_operator do 
    role Role.find_or_create_by(role_title: "Event Operator", name: "event_operator") 
    email "[email protected]" 
    end 

    trait :athletic_trainer do 
    role Role.find_or_create_by(role_title: "Athletic Trainer", name: "athletic_trainer") 
    email "[email protected]" 
    end 

end 
end 

正如你可以看到我使用trait S代表定義用戶的角色,和設置不同的電子郵件地址。

我有另一種模式叫Event,事件屬於athletic_trainer這是該協會的名稱,它只是指向用戶的模式,所以我用工廠女孩爲創建這樣一個事件:

FactoryGirl.define do 

    factory :event do 
     event_type Event.event_types[:tournament] 
     sport Event.sports[:lacrosse] 
     event_title "NXT Cup" 
     event_logo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'images', 'nxt_cup_logo.png')) } 
     gender Event.genders[:boys] 
     event_pay_rate 40 
     event_participant_numbers 3 
     event_feature_photo { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'images', 'nxt_cup_feature.jpg')) } 
     event_description "We roll out the red carpet for North America's top youth talent. The nations top youth teams descend on the premier facilities in the Philadelphia region to battle it out and stake claim to one of the summers most highly coveted trophies...the NXT Cup." 
     event_operator 
    end 

    end 

,你可以看到我添加了event_operator在的情況下,工廠的女孩結束了指定用戶的關聯,但是這樣一來,我沒有獲得在工廠女孩關聯的用戶。

是有可能發送athletic_trainer作爲參數傳遞給該事件的工廠女孩​​?我的意思是我想創建用戶使用工廠女孩,然後創建事件,但關聯剛剛創建的用戶,這可能嗎?

回答

1

您可以隨時將它們傳遞給buildcreate方法覆蓋領域。要將event_operator設置爲您所需的user,您應該這樣做:

user = build(:user) 
event = build(:event, event_operator: user)