Mongoid Polymorphic Association + FactoryGirl + RSpec

时间:2012-06-29 11:22:43

标签: mongoid factory-bot

我正在尝试使用多态方法在Mongoid对象中嵌入电子邮件。获取“BSON :: InvalidDocument:无法将类Mongoid :: Relations :: Embedded :: Many的对象序列化为BSON。”每当我运行测试。请参阅下面的代码,我们将不胜感激。我不确定在FactoryGirl中建立电子邮件的正确方法是什么。感谢。

class Email
  include Mongoid::Document
  include Mongoid::Timestamps
  embedded_in :mailable, polymorphic: true

  field :email, type: String
  field :category, type: String
end

class Person
  include Mongoid::Document
  embeds_many :emails, as: :mailable       #polymorhpic
  index  "emails.email", unique: true

  field :first_name, type: String
  field :middle_name, type: String
  field :last_name, type: String

  validates_uniqueness_of :emails

end


FactoryGirl.define do
  sequence(:fn) {|n| "first_name#{n}" }
  sequence(:ln) {|n| "last_name#{n}" }
  factory :person do
    first_name { generate(:fn) }
    last_name { generate(:ln) }
    gender 'M'
    nationality 'USA'
    ssn '123-88-1111'
    factory :emails_ do
      emails { Factory.build(:email) }
    end
  end
end

FactoryGirl.define do
  sequence(:address) {|n| "user#{n}@mail.com" }
  factory :email do
    email { generate(:address) }
    category 'personal'
  end
end

1 个答案:

答案 0 :(得分:0)

这是我上次在mongoid中使用具有嵌入式关联的Factory Girl时采用的方法。请在您的用户工厂中尝试此操作。

emails { |e| [e.association(:email)] }