Rails Factory Girl:创建与用户相关但具有角色的记录

时间:2016-05-01 20:46:25

标签: ruby-on-rails ruby-on-rails-4 factory-bot

我有以下工厂女孩为创建用户:

test_str

如您所见,我使用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 "cash@cash.com" end trait :athletic_trainer do role Role.find_or_create_by(role_title: "Athletic Trainer", name: "athletic_trainer") email "cash1@cash.com" end end end 来定义用户的角色,并设置不同的电子邮件地址。

我有另一个名为trait的模型,一个属于Event的事件,它是关联的名称,它只是指向User模型,所以我使用Factory Girl来创建这样的事件:

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 以指定用户关联,但是这样我就无法访问工厂女孩中关联的用户。

是否可以将sports_trainer作为参数发送给活动的工厂女孩​​?我的意思是我想使用工厂女孩创建用户,然后创建事件但关联我刚创建的用户,这可能吗?

1 个答案:

答案 0 :(得分:1)

您始终可以通过将字段传递给buildcreate方法来覆盖字段。要将event_operator设置为您想要的user,您可以这样做:

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