所以我正在玩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方式。好像应该有。
提前致谢!
答案 0 :(得分:11)
您也可以这样做,如Factory Girl + Mongoid embedded documents in fixtures中所述:
FactoryGirl.define do
factory :profile do |f|
#fields
address { FactoryGirl.build(:address) }
end
end
答案 1 :(得分:3)
尝试使用build_address
代替create_address
。在我看来,你的工厂已经坏了,因为在创建配置文件记录之前,你正试图创建一个地址记录。 build_*
应该为父模型分配所有必要的属性,以后它应该与其嵌入的关系一起保存。