FactoryGirl & Mongoid embedded_in and build_list

factory-bot, mongoid, rspec

Solution

When I first switched from Active Record to Mongoid, I had a lot of trouble getting Factory Girl to play nice. I ended up switching to Fabrication - which supports Mongoid out of the box.

Problem

The Issue Okay so the issue I am having is with FactoryGirl building embedded assignments in my Quiz which uses mongo instead of active record. I tried using a build_list which works with my active record models, but I am having an issue with doing this with mongoid... I am able to call the following and get quiz_assignments back: ``` @quiznos.quiz_assignments.new(due_at: Time.now+ 1.day, published_at: Time.now) ``` However if I call ``` @quiznos = FactoryGirl.build(:quizWassignments) ``` @quiznos will have a created quiz, but @quiz.quiz_assignments == [] I can even run the following and have past ``` @quiz = FactoryGirl.build(:quiz) @quiznos = FactoryGirl.build(:quiz_assignment, quiz: @quiz) @quiz.quiz_assignments.should == [@quiznos] ``` The Question Is there a way to get this to work with :quizWassignments? The Code ``` class Quiz include Mongoid::Document include Mongoid::Timestamps field :user_id field :title field :description field :assignment_id field :due_at, :type => DateTime field :published_at, :type => DateTime embeds_many :quiz_assignments end class QuizAssignment include Mongoid::Document include Mongoid::Timestamps field :due_at, :type => DateTime field :published_at, :type => DateTime embedded_in :quiz embeds_many :quiz_assignees validates_presence_of :due_at, :published_at validates_associated :quiz_assignees end FactoryGirl.define do factory :quiz do title { Factory.next(:name) } description { Factory.next(:description) } quiz_type "Practice" factory :quizWassignments do ignore do count 3 end after_create do |quiz, evaluator| FactoryGirl.build_list(:quiz_assignment, evaluator.count, quiz: quiz) end end end factory :quiz_assignment do due_at Time.now + 1.day published_at Time.now end end ```

Original source