Factory Girl + Mongoid嵌套文档在固定装置中的应用

37

假设你有以下的 Mongoid 文档:

class User
    include Mongoid::Document
    embeds_one :name
end

class UserName
    include Mongoid::Document
    field :first
    field :last_initial

    embedded_in :user
end

如何创建一个 Factory Girl 工厂,初始化嵌入式文档的名字和姓氏首字母缩写?还有,如果使用embeds_many关系,该如何实现呢?

2个回答

63

我也在寻找这个问题的答案,在研究过程中,我遇到了许多代码,并将它们拼凑在一起(虽然我希望有更好的文档),但这是我代码的一部分。地址是一个1..1关系,电话是一个1..n关系到事件。

  factory :event do
    title     'Example Event'

    address  { FactoryGirl.build(:address) }
    phones    { [FactoryGirl.build(:phone1), FactoryGirl.build(:phone2)] }
  end

  factory :address do
    place     'foobar tower'
    street    'foobar st.'
    city      'foobar city'
  end

  factory :phone1, :class => :phone do
    code      '432'
    number    '1234567890'
  end

  factory :phone2, :class => :phone do
    code      '432'
    number    '0987654321'
  end

(如果我无法提供我的链接,很抱歉,它们有点混乱)


谢谢。我刚刚浪费了几个小时来追踪这个问题。 - Tyler Gannon
1
请注意,phones属性是一个数组(FactoryGirl调用被包含在[]中)。如果关系是embeds_many,则您不需要多个:phone,但它必须是一个数组。这个细节让我浪费了大约4个小时! - SteveO7

6
这里有一个解决方案,可以动态定义嵌入对象的数量:
FactoryGirl.define do
  factory :profile do
    name 'John Doe'
    email 'john@bigcorp.com'
    user

    factory :profile_with_notes do
      ignore do
        notes_count 2
      end

      after(:build) do |profile, evaluator|
        evaluator.notes_count.times do
          profile.notes.build(FactoryGirl.attributes_for(:note))
        end
      end
    end
  end
end

这使得你可以调用 FactoryGirl.create(:profile_with_notes) 来获取两个嵌入式笔记,或者调用 FactoryGirl.create(:profile_with_notes, notes_count: 5) 来获取五个嵌入式笔记。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接