我很确定我在这里遗漏了一些非常基本的东西。
我想测试是否 before_save
callback 做它应该做的事情,而不仅仅是它被调用。
我写了以下测试:
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 为“got: nil”而不是“lecture”
由于我没有发现我的实现代码有任何明显的错误,我在我的开发环境中尝试了回调,它实际上在向 question_type 添加“讲座”时起作用。
这让我觉得我的测试可能有问题。我在这里缺少什么?是否
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
里面声明,看看会发生什么。
关于ruby-on-rails-3 - 使用 Rspec 和 Factory Girl 测试 before_save 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088362/