Testing before_save callback with Rspec and Factory Girl

I am sure that I am missing something really basic.

I want to check if the before_save callback before_save what it should do, and not just what it is called.

I wrote the following test:

 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 

And I have the following factories for course and 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 

And I wrote the following callback in my question model:

 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 

The test continues to fail, saying that "got: no" for question_type instead of "lecture"

Since I did not see anything clearly wrong with my implementation code, I tried the callback in my development environment, and in fact it worked with the addition of a β€œlecture” in question_type.

It makes me think there might be something wrong with my test. What am I missing here? Does Factory.create default callbacks?

+6
source share
1 answer

I would not use Factory.create to start the process. FactoryGirl should be used to create a test setup, and not to run the actual code that you want to test. Then your test will look like this:

 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 

If this test still fails, you can start debugging:

Add the puts statement inside add_type_to_question and another inside the if and see what happens.

+4
source

Source: https://habr.com/ru/post/907356/


All Articles