0

Here is my Lesson model:

before_create :set_sequence

def set_sequence
  maxseq = Lesson.where(:course_id => self.course_id).maximum("sequence")
  if (maxseq.nil?)
    maxseq = 0
  end
  self.sequence = maxseq + 1
end

when I run rspec the following test fails:

it "validate sequence is setup" do
  lesson = Lesson.create(:title => "Testing", :description => "Testing", :course_id => 1)
  lesson.sequence.should_not eql nil
end

However when T test this through rails console the Lesson object is created successfully and with the correct sequence. Any ideas why?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214

3 Answers3

0

lesson.sequence.should_not be_nil is the correct way to test for nil, as far as I know. Have you tried that?

p.matsinopoulos
  • 7,655
  • 6
  • 44
  • 92
0

Any validations you've got on Lesson could be silently aborting the create before your callback gets called. Change it to create! in the spec to check it.

regularfry
  • 3,248
  • 2
  • 21
  • 27
0

FactoryGirl first initializes object with no parameters, and then assigns parameters one by one. The callback in your model probably would not work in this case. So you can try to change FactoryGirl's behavior by adding

initialize_with { new(attributes) }

to the Lesson's factory. I'm not sure it will help though. Testing callback behavior in Rails is tricky.

denis.peplin
  • 9,585
  • 3
  • 48
  • 55