使用Factory_Girl设置嵌入式Mongoid模型

Dre*_*rew 5 rspec mongoid ruby-on-rails-3 factory-bot

所以我正在玩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
Run Code Online (Sandbox Code Playgroud)

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

FactoryGirl.define do
  factory :profile do
    #fields

    address
  end
end
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误:

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.
Run Code Online (Sandbox Code Playgroud)

通过将工厂更改为以下内容,我得到了它的工作:

FactoryGirl.define do
  factory :profile do
    #fields

    after(:build) do |p| 
      p.create_address(FactoryGirl.attributes_for(:address))
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这有效,但我希望有一个更原生的Factory_Girl方式来做到这一点.好像应该有.

提前致谢!

小智 11

你也可以这样做,就像在夹具中的Factory Girl + Mongoid嵌入文档中引用的那样:

FactoryGirl.define do
  factory :profile do |f|
    #fields
    address { FactoryGirl.build(:address) }
  end
end
Run Code Online (Sandbox Code Playgroud)


lua*_*sus 3

尝试使用build_address而不是create_address. 在我看来,您的工厂已损坏,因为您试图在保存(创建)配置文件记录之前创建地址记录。build_*应将所有必要的属性分配给父模型,然后应将其与其嵌入的关系一起保留。