【发布时间】:2009-11-03 22:57:51
【问题描述】:
我正在寻找一种方法来加快我的 Shoulda + FactoryGirl 测试。
我正在尝试测试的模型 (StudentExam) 与其他模型有关联。在创建StudentExam 之前,这些关联对象必须存在。因此,它们是在setup 中创建的。
但是,我们的一个模型 (School) 需要大量时间来创建。因为setup 在每个should 语句之前被调用,所以整个测试用例需要很长时间才能执行——它为每个执行的应该语句创建一个新的@school、@student、@topic 和@exam。
我正在寻找一种方法来创建这些对象一次并且只创建一次。是否有类似startup for before_all 方法的东西可以让我创建将在整个测试用例的其余部分持续存在的记录?
基本上,我正在寻找与 RSpec 的 before(:all) 完全相同的东西。我不关心依赖问题,因为这些测试永远不会修改那些昂贵的对象。
这是一个示例测试用例。为长代码道歉(我还创建了一个gist):
# 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
【问题讨论】:
标签: ruby-on-rails testing shoulda factory-bot