Skip to content

Instantly share code, notes, and snippets.

@petRUShka
Last active August 29, 2015 14:06
Show Gist options
  • Save petRUShka/cbad53eab23ca680516d to your computer and use it in GitHub Desktop.
Save petRUShka/cbad53eab23ca680516d to your computer and use it in GitHub Desktop.
be_observed_by matcher
require 'rspec/expectations'
RSpec::Matchers.define :be_observed_by do |observer_name|
match do |obj|
ActiveRecord::Base.observers.enable observer_name
observer = observer_class(observer_name)
# save old after_create and define new
was_defined = observer.method_defined?(:after_create)
unless was_defined
observer.class_eval do
define_method(:after_create) {}
end
observer.instance.instance_eval do
define_callbacks(obj.class)
end
end
observer.instance.should_receive(:after_create)
obj.save(validate: false)
# revert monkey patching
unless was_defined
observer.class_eval do
remove_method(:after_create)
end
observer.instance.instance_eval do
define_callbacks(obj.class)
end
end
begin
RSpec::Mocks::verify # run mock verifications
true
rescue RSpec::Mocks::MockExpectationError => e
# here one can use #{e} to construct an error message
false
end
end
failure_message_for_should do
"expected #{actual.class} to be observed by #{observer_class(observer_name)}"
end
def observer_class(observer_name)
observer_name.to_s.camelize.constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment