Is there an easy way to test ActiveRecord callbacks in Rspec?

Suppose I have the following ActiveRecord class:

class ToastMitten < ActiveRecord::Base before_save :brush_off_crumbs end 

Is there a clean way to verify that :brush_off_crumbs was set as a before_save ?

By "clean" I mean:

  • "Without actual retention" because
    • He is slow
    • I do not need to verify that ActiveRecord is correctly managing the before_save directive; I need to verify that I correctly said what to do before saving it.
  • "Without hacking through undocumented methods"

I found a way that meets criteria # 1 but not # 2:

 it "should call have brush_off_crumbs as a before_save callback" do # undocumented voodoo before_save_callbacks = ToastMitten._save_callbacks.select do |callback| callback.kind.eql?(:before) end # vile incantations before_save_callbacks.map(&:raw_filter).should include(:brush_off_crumbs) end 
+6
source share
1 answer

Use run_callbacks

This is less dangerous, but not ideal:

 it "is called as a before_save callback" do revenue_object.should_receive(:record_financial_changes) revenue_object.run_callbacks(:save) do # Bail from the saving process, so we'll know that if the method was # called, it was done before saving false end end 

Using this technique to test after_save would be more inconvenient.

+9
source

All Articles