3

我正在使用 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工厂从不声明与配方的关联。如果我确实声明了与配方的关联,那么我会得到一个无限循环,因为配方与成分相关联,而成分与配方相关联。这很烦人,因为我无法正确地对我的成分类进行单元测试。我怎么解决这个问题?

4

1 回答 1

4

如果您的目标只是对嵌入的成分类进行单元测试,那么最好避免完全“创建”到数据库中,而只需实例化对象...

FactoryGirl.build(:ingredient)  

这样可以避免将对象实际持久化到 MongoDB 中。否则,从 Mongoid/MongoDB 的角度来看,嵌入文档不能在没有父级的情况下存在于数据库中,因此如果您必须将对象持久保存到数据库中,则必须通过父级来完成。

于 2013-03-20T20:28:28.293 回答