如何使用FactoryGirl创建嵌入式文档?

时间:2023-01-29 15:49:31

I am using FactoryGirl and RSpec to test my code. Mongoid in my ORM. The problem I am encountering is that in order create an embedded document, you must also create the parent document. Here is an example:

我正在使用factory - girl和RSpec来测试我的代码。Mongoid ORM。我遇到的问题是,为了创建一个嵌入的文档,您还必须创建父文档。这是一个例子:

# 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

Then I make factories for both of these:

然后我为这两个做工厂:

# 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

The problem I have now is that I cannot ever call FactoryGirl.create(:ingredient). The reason being that Ingredient is embedded, and my Ingredient factory never declares the association to the Recipe. If I do declare an association to the recipe, then I get an infinite loop because the Recipe associates with the Ingredient, and the Ingredient associates with the Recipe. The is quite annoying because I can't unit test my Ingredient class correctly. How can I solve this problem?

我现在遇到的问题是,我不能调用factory .create(: component)。原因是配料是嵌入的,我的配料工厂从来没有声明与配方的关联。如果我确实声明了与配方的关联,那么我将得到一个无限循环,因为配方与配方相关,而配方与配方相关。这很烦人,因为我不能正确地单元测试我的成分类。我如何解决这个问题?

1 个解决方案

#1


4  

If your goal is simply to unit-test the embedded Ingredient class, then it would be best to avoid doing a 'create' into the database altogether, and simply instantiate the object ala...

如果您的目标仅仅是单元测试内嵌的component类,那么最好避免在数据库中执行“创建”操作,并简单地实例化对象ala……

FactoryGirl.build(:ingredient)  

That would avoid actually persisting the object into MongoDB. Otherwise, from a Mongoid/MongoDB perspective the embedded document can't exist in the database without the parent, so if you must persist the object into the DB you will have to do it via the parent.

这将避免将对象持久化到MongoDB中。否则,从Mongoid/MongoDB的角度来看,如果没有父类,嵌入的文档就不能存在数据库中,所以如果必须将对象持久化到DB中,就必须通过父类来实现。

#1


4  

If your goal is simply to unit-test the embedded Ingredient class, then it would be best to avoid doing a 'create' into the database altogether, and simply instantiate the object ala...

如果您的目标仅仅是单元测试内嵌的component类,那么最好避免在数据库中执行“创建”操作,并简单地实例化对象ala……

FactoryGirl.build(:ingredient)  

That would avoid actually persisting the object into MongoDB. Otherwise, from a Mongoid/MongoDB perspective the embedded document can't exist in the database without the parent, so if you must persist the object into the DB you will have to do it via the parent.

这将避免将对象持久化到MongoDB中。否则,从Mongoid/MongoDB的角度来看,如果没有父类,嵌入的文档就不能存在数据库中,所以如果必须将对象持久化到DB中,就必须通过父类来实现。