How do I create inline documents with FactoryGirl?

I am using FactoryGirl and RSpec to test my code. Mongoid in my ORM. The problem I'm running into is that in order to create an inline document, you must also create a parent document. Here's an example:

# 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 create factories for both of them:

# 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

      

Now the problem is that I can never call FactoryGirl.create (: component). The reason is because it Ingredient

is Ingredient

inline and my factory never declares a link to the Recipe. If I declare an association with a recipe, I get an infinite loop, because the Recipe is associated with the Ingredient, and the Ingredient is associated with the Recipe. This is pretty annoying because I can't unit test the Ingredient class correctly. How can I solve this problem?

+3


source to share


1 answer


If your goal is simply to test the built-in Ingredient class, then it might be better to "create" in the database at all and just instantiate the ala object ...

FactoryGirl.build(:ingredient)  

      



This will avoid actually saving the object to MongoDB. Otherwise, from a Mongoid / MongoDB perspective, an embedded document cannot exist in a database without a parent, so if you have to transfer an object to the database, you will have to do it through the parent.

+4


source







All Articles