Factory Girl + Mongoid embedded documents in fixtures

GTDev picture GTDev · Sep 24, 2011 · Viewed 10.6k times · Source

Let’s say you have the following mongoid documents:

class User
    include Mongoid::Document
    embeds_one :name
end

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

    embedded_in :user
end

How do you create a factory girl factory which initializes the embedded first name and last initial? Also how would you do it with an embeds_many relationship?

Answer

index picture index · Oct 4, 2011

I was also looking for this one and as I was researching I've stumbled on a lot of code and did pieced them all together (I wish there were better documents though) but here's my part of the code. Address is a 1..1 relationship and Phones is a 1..n relationship to events.

  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

(And sorry if I can't provide my links, they were kinda messed up)