1

Here's my test:

require 'spec_helper'

describe League do

    it 'should default weekly to false' do
      league = Factory.create(:league, :weekly => nil)
      league.weekly.should == false
    end
  end

end

And here's my model:

class League < ActiveRecord::Base

  validates :weekly, :inclusion => { :in => [true, false] }

  before_create :default_values

  protected

  def default_values
    self.weekly ||= false
  end

end

When I run my test, I get the following error message:

 Failure/Error: league = Factory.create(:league, :weekly => nil)
 ActiveRecord::RecordInvalid:
   Validation failed: Weekly is not included in the list

I've tried a couple different approaches to trying to create a league record and trigger the callback, but I haven't had any luck. Is there something that I am missing about testing callbacks using RSpec?

keruilin
  • 16,782
  • 34
  • 108
  • 175
  • Validation is run on the model before the before_create is triggered so that's why I am getting the error. I decided to go this route: http://stackoverflow.com/questions/6715468/attr-accessor-default-values/8775320#8775320. Now all works. – keruilin Jan 13 '12 at 02:53

1 Answers1

2

I believe that what you are saying is, before create, set weekly to false, then create actually sets weekly to nil, overwriting the false.

Just do

require 'spec_helper'

describe League do

    it 'should default weekly to false' do
      league = Factory.create(:league)  # <= this line changed
      league.weekly.should == false
    end
  end

end

in your test. No need to explicitly set nil.

Kyle Heironimus
  • 7,741
  • 7
  • 39
  • 51