我正在寻找一种方法来加快我的Shoulda + FactoryGirl测试。
我要测试的模型 ( StudentExam
) 与其他模型有关联。这些关联对象必须存在,然后我才能创建StudentExam
. 因此,它们是在setup
.
但是,我们的模型之一 ( School
) 需要大量时间来创建。因为setup
在每条语句之前都被调用should
,所以整个测试用例需要 eons 来执行——它为每个执行的 should 语句创建一个新@school
的@student
,@topic
和。@exam
我正在寻找一种方法来创建这些对象一次且仅一次。是否有类似startup
forbefore_all
方法的东西可以让我创建将在整个测试用例的其余部分持续存在的记录?
基本上我正在寻找与 RSpec 完全相同的东西before(:all)。我不关心依赖问题,因为这些测试永远不会修改那些昂贵的对象。
这是一个示例测试用例。为长代码道歉(我还创建了一个要点):
# A StudentExam represents an Exam taken by a Student.
# It records the start/stop time, room number, etc.
class StudentExamTest < ActiveSupport::TestCase
should_belong_to :student
should_belong_to :exam
setup do
# These objects need to be created before we can create a StudentExam. Tests will NOT modify these objects.
# @school is a very time-expensive model to create (associations, external API calls, etc).
# We need a way to create the @school *ONCE* -- there's no need to recreate it for every single test.
@school = Factory(:school)
@student = Factory(:student, :school => @school)
@topic = Factory(:topic, :school => @school)
@exam = Factory(:exam, :topic => @topic)
end
context "A StudentExam" do
setup do
@student_exam = Factory(:student_exam, :exam => @exam, :student => @student, :room_number => "WB 302")
end
should "take place at 'Some School'" do
assert_equal @student_exam, 'Some School'
end
should "be in_progress? when created" do
assert @student_exam.in_progress?
end
should "not be in_progress? when finish! is called" do
@student_exam.finish!
assert !@student_exam.in_progress
end
end
end