Phi*_*p V 6 rspec2 ruby-on-rails-3 factory-bot
我很确定我错过了一些非常基本的东西.
我想测试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
Run Code Online (Sandbox Code Playgroud)
我有以下工厂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
Run Code Online (Sandbox Code Playgroud)
我在我的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
Run Code Online (Sandbox Code Playgroud)
对于question_type而不是'讲座',测试仍然失败说"得到:nil"
由于我没有看到任何明显错误的实现代码,我在开发环境中尝试了回调,它实际上有助于将"讲座"添加到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
Run Code Online (Sandbox Code Playgroud)
如果此测试仍然失败,您可以开始调试:
在语句中添加puts语句,在语句中添加add_type_to_question另一个if语句,看看会发生什么.
| 归档时间: |
|
| 查看次数: |
4506 次 |
| 最近记录: |