4

问题

好的,所以我遇到的问题是 FactoryGirl 在我的测验中构建嵌入式作业,它使用 mongo 而不是活动记录。我尝试使用与我的活动记录模型一起使用的 build_list,但我在使用 mongoid 时遇到了问题......

我可以调用以下命令并取回 quiz_assignments:

@quiznos.quiz_assignments.new(due_at: Time.now+ 1.day, published_at: Time.now)

但是,如果我打电话

@quiznos = FactoryGirl.build(:quizWassignments)

@quiznos 将创建一个测验,但 @quiz.quiz_assignments == []

我什至可以运行以下命令并过去

@quiz = FactoryGirl.build(:quiz)
@quiznos = FactoryGirl.build(:quiz_assignment, quiz: @quiz)
@quiz.quiz_assignments.should == [@quiznos]

问题

有没有办法让它与 :quizWassignments 一起使用?

编码

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
4

1 回答 1

6

当我第一次从 Active Record 切换到 Mongoid 时,我很难让 Factory Girl 玩得好。我最终切换到了Fabrication - 它支持开箱即用的 Mongoid。

于 2012-05-03T03:37:44.263 回答