【问题标题】:Setting up Embedded Mongoid Models with Factory_Girl使用 Factory_Girl 设置嵌入式 Mongoid 模型
【发布时间】:2012-10-15 15:01:25
【问题描述】:

所以我正在使用 Mongoid、Rspec 和 Factory_Girl,但我在嵌入文档时遇到了一些问题。

我有以下型号:

class Profile    
   include Mongoid::Document

   #Fields and stuff
      embeds_one :address

   validates :address, presence: true 
end

class Address    
   include Mongoid::Document

   #Fields and stuff
      embedded_in :profile 
end

所以当我这样定义工厂时:

FactoryGirl.define do
  factory :profile do
    #fields

    address
  end
end

我收到这样的错误:

Failure/Error: subject { build :profile }
     Mongoid::Errors::NoParent:

       Problem:
         Cannot persist embedded document Address without a parent document.
       Summary:
         If the document is embedded, in order to be persisted it must always have a reference to it's parent document. This is most likely cause by either calling Address.create or Address.create! without setting the parent document as an attribute.
       Resolution:
         Ensure that you've set the parent relation if instantiating the embedded document direcly, or always create new embedded documents via the parent relation.

我通过将工厂更改为这样的方式使其工作:

FactoryGirl.define do
  factory :profile do
    #fields

    after(:build) do |p| 
      p.create_address(FactoryGirl.attributes_for(:address))
    end
  end
end

这可行,但我希望有一种更原生的 Factory_Girl 方式来执行此操作。好像应该有。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails-3 rspec mongoid factory-bot


    【解决方案1】:

    您也可以这样做,如 Factory Girl + Mongoid embedded documents in fixtures 中所述:

    FactoryGirl.define do
      factory :profile do |f|
        #fields
        address { FactoryGirl.build(:address) }
      end
    end
    

    【讨论】:

    【解决方案2】:

    尝试使用build_address 而不是create_address。在我看来,您的工厂已损坏,因为您试图在保留(创建)个人资料记录之前创建地址记录。 build_* 应该将所有必要的属性分配给父模型,然后它应该与它的嵌入关系一起被持久化。

    【讨论】:

    • 很公平,但 FactoryGirl 是否没有办法在没有回调的情况下处理这个问题?
    • 我不这么认为,这是 mongodb / mongoid 特定的东西。
    猜你喜欢
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    相关资源
    最近更新 更多