【问题标题】:How do you create embedded documents using FactoryGirl?如何使用 FactoryGirl 创建嵌入式文档?
【发布时间】:2013-01-21 23:12:26
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 mongoid factory-bot


    【解决方案1】:

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

    FactoryGirl.build(:ingredient)  
    

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

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 2013-06-29
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多