在工厂定义中,使用其他工厂的属性分配属性

时间:2012-03-16 13:47:01

标签: ruby factory-bot

我有两个factory_girl工厂,contactuser。 Contact有一个属性dest_user_id,它是user的外键,但可以为NULL。对于该属性,我想使用user工厂创建新用户,然后将其ID分配给dest_user_id。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

如果关系保持与模型名称相同,则具有dest_user_id的外键不应更改方法。假设contact belongs_to useruser has_onehas_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_idNULLFactoryGirl.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),则会自动创建contactuser,但您无法控制使用时dest_user_id的分配FactoryGirl.create(:contact_with_user, :user => @user)