Skip to content

Instantly share code, notes, and snippets.

@millisami
Forked from justinko/callback_disabler.rb
Created November 11, 2011 10:23
Show Gist options
  • Save millisami/1357680 to your computer and use it in GitHub Desktop.
Save millisami/1357680 to your computer and use it in GitHub Desktop.
Disable raw filter callbacks in RSpec
# In spec/support/callback_disabler.rb
module CallbackDisabler
def self.store_callbacks(model, filters)
model = constantize(model)
filters.each do |filter|
model.send("_#{filter}_callbacks").each do |callback|
stored_callbacks[model] << {
filter: filter, kind: callback.kind, raw_filter: callback.raw_filter
}
end
end
end
def self.remove_callbacks(model, filters)
model = constantize(model)
filters.each do |filter|
model.reset_callbacks(filter)
end
end
def self.reset_callbacks
stored_callbacks.each do |model, callbacks|
callbacks.each do |callback|
model.set_callback(
callback[:filter], callback[:kind], callback[:raw_filter]
)
end
end
end
def self.clear
stored_callbacks.clear
end
def self.stored_callbacks
@stored_callbacks ||= Hash.new {|h,k| h[k]=[]}
end
def self.constantize(model)
model.to_s.camelize.constantize
end
end
def disable_callbacks(model, *filters)
before do
CallbackDisabler.store_callbacks(model, filters)
CallbackDisabler.remove_callbacks(model, filters)
end
after do
CallbackDisabler.reset_callbacks
CallbackDisabler.clear
end
end
# Your model
class MyClass
after_update MyCallback.new
class MyCallback
def after_update(instance)
end
end
end
# In your specs, call it like this
describe MyClass do
disable_callbacks :my_class, :update
# ...
end
@millisami
Copy link
Author

Is there any other way to disable callback based on the name of the method?

e.g.

class MyClass < ActiveRecord::Base
  after_create :notify
  after_create :sanitize

end

describe MyClass
  disable_callbacks :my_class, :create
end

In the above case both callbacks gets disabled.
How to just disable the :notify callback only?

@justinko
Copy link

I never got this comment because you made it on your own gist! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment