Skip to content

Instantly share code, notes, and snippets.

@justinko
Created September 2, 2011 00:20
Show Gist options
  • Save justinko/1187650 to your computer and use it in GitHub Desktop.
Save justinko/1187650 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment