我很确定我在这里确实缺少一些基本知识。
我想测试before_save
回调是否完成了应做的事情,而不仅仅是调用了它。
我写了以下测试:
it 'should add lecture to question_type' do
@course = Factory :course,
:start_time => Time.now - 1.hour,
:end_time => Time.now
@question = Factory.create(:question,
:course_id => @course.id,
:created_at => Time.now - 10.minutes)
@question.question_type.should == 'lecture'
end
我有以下用于
course
和question
的工厂:Factory.define :course do |c|
c.dept_code {"HIST"}
c.course_code { Factory.next(:course_code) }
c.start_time { Time.now - 1.hour }
c.end_time { Time.now }
c.lecture_days { ["Monday", Time.now.strftime('%A'), "Friday"] }
end
Factory.define :question do |q|
q.content {"Why don't I understand this class!?"}
q.association :course
end
我在
Question
模型中编写了以下回调:before_save :add_type_to_question
protected
def add_type_to_question
@course = Course.find(self.course_id)
now = Time.now
if (time_now > lecture_start_time && time_now < lecture_end_time ) && @course.lecture_days.map{|d| d.to_i}.include?(Time.now.wday)
self.question_type = "lecture"
end
end
测试不断失败,对question_type而不是“lecture”说“got:nil”
由于我的实现代码没有发现任何明显的错误,因此我在开发环境中尝试了该回调,并且实际上可以在question_type中添加“lecture”。
这使我认为我的测试可能有问题。我在这里想念什么?默认情况下,
Factory.create
是否跳过回调? 最佳答案
我不会使用Factory.create
来触发该过程。应该使用FactoryGirl创建测试设置,而不是触发要测试的实际代码。您的测试将如下所示:
it 'should add lecture to question_type' do
course = Factory(:course, :start_time => Time.now - 1.hour, :end_time => Time.now)
question = Factory.build(:question, :course_id => course.id, :created_at => Time.now - 10.minutes, :question_type => nil)
question.save!
question.reload.question_type.should == 'lecture'
end
如果此测试仍然失败,则可以开始调试:
在
add_type_to_question
内添加一个puts语句,在if
语句内添加另一个语句,看看会发生什么。