私はここで本当に基本的なものがないと確信しています。Rspecと工場の女の子で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
ため、次の工場を持っている:
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
テストでは、f 「講義」の代わりにquestion_typeに「got:nil」と言っていることを言っている
私の実装コードで明らかに間違ったことは何もなかったので、開発環境でコールバックを試みました。質問の種類。
これは私のテストで何か問題があるかもしれないと思います。私はここで何が欠けていますか? Factory.create
はデフォルトでコールバックをスキップしますか?
before_saveの代わりにtry before_validation – cpuguy83