所以我在玩 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 方式来做到这一点。好像应该有。
提前致谢!