我有两个factory_girl工厂,contact
和user
。 Contact有一个属性dest_user_id
,它是user
的外键,但可以为NULL。对于该属性,我想使用user
工厂创建新用户,然后将其ID分配给dest_user_id
。有没有办法做到这一点?
答案 0 :(得分:0)
如果关系保持与模型名称相同,则具有dest_user_id
的外键不应更改方法。假设contact
belongs_to
user
和user
has_one
或has_many
contacts
,您可以实现以下目标: :
首先创建工厂:
FactoryGirl.define do
factory :user do
Field 1
Field 2
# etc
end
factory :contact do
# Add only the minimum fields required to create a contact, but not the association
Field 1
Field 2
factory :contact_with_user do
# then you add the association for this inherited factory
# we can use 'user' here as the factory is the same as the association name
user
end
end
end
使用此设置,您可以创建contact
而不是user
,因此当您在测试/规范中使用dest_user_id
时NULL
为FactoryGirl.create(:contact)
。< / p>
要创建user
并将ID分配到dest_user_id
上的contact
字段,您将使用以下内容:
@user = FactoryGirl.create(:user)
@contact = FactoryGirl.create(:contact_with_user, :user => @user)
这种方法可以最大限度地提高灵活性,因为您可以在有或没有用户的情况下创建contact
,只有在特定测试需要时才能将user.id
传递给联系人模型。如果您致电FactoryGirl.create(:contact_with_user)
,则会自动创建contact
和user
,但您无法控制使用时dest_user_id
的分配FactoryGirl.create(:contact_with_user, :user => @user)