我正在使用 FactoryGirl 和 RSpec 来测试我的代码。我的 ORM 中的 Mongoid。我遇到的问题是,为了创建嵌入文档,您还必须创建父文档。这是一个例子:
# app/models/recipe.rb
class Recipe
include Mongoid::Document
field :title
embeds_many :ingredients
end
# app/models/ingredient.rb
class Ingredient
include Mongoid::Document
field :name
embedded_in :recipe
end
然后我为这两个制造工厂:
# spec/factories/recipes.rb
FactoryGirl.define do
factory :recipe do |f|
f.title "Grape Salad"
f.association :ingredient
end
end
# spec/factories/ingredients.rb
FactoryGirl.define do
factory :ingredient do |f|
f.name "Grapes"
end
end
我现在遇到的问题是我永远无法调用 FactoryGirl.create(:ingredient)。原因Ingredient
是嵌入的,我的Ingredient
工厂从不声明与配方的关联。如果我确实声明了与配方的关联,那么我会得到一个无限循环,因为配方与成分相关联,而成分与配方相关联。这很烦人,因为我无法正确地对我的成分类进行单元测试。我怎么解决这个问题?