6
我很确定我错过了这里真正基本的东西。使用Rspec和Factory Girl测试before_save回调
我想测试一个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
以下工厂:
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
:
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
模型写了下面的回调
测试保持f因为我没有看到我的实现代码有什么明显的错误,所以我在我的开发环境中尝试了回调,并且它实际上在'lecture'中添加了'lecture'问题类型。
这让我觉得我的测试可能有问题。我在这里错过了什么? Factory.create
默认跳过回调吗?
而不是before_save尝试before_validation – cpuguy83 2012-11-19 20:02:37