Search code examples
ruby-on-railsruby-on-rails-3stubbefore-filter

rails, mock before_filter


I have a number of models that should be "finished" in a couple of days after creation. I've made a before_filter that finds all models that should be finished and finishes them. The problem is that I can't figure out how to write spec for the same. The models are validated like this: ( pseudo validation ):

validates :till, date: { later_than: 2.days.from_now.to_date, earlier_than: 8.days.from_now.to_date }

the before_filter looks like this:

@models = Model.where(['till <= ? AND finished = ?', Time.now.to_date, false])
   @models.each do |model|
     model.update_attributes(finished: true)
   end
end

So to make my before_filter find the tested model I can save it with fake date(i.e 5.days.ago) by passing validate: false

But in before filter the update_attributes call will return false since model has a wrong date.

Could you please advice how can I make before_filter skip the validations in a context of a single test case?


Solution

  • you should add a :on => :create to your validation, so that calling update_attributes in your before_filter won't trigger it.