Skip to content

Instantly share code, notes, and snippets.

@itarato
Last active April 24, 2024 19:57
Show Gist options
  • Save itarato/80e29ab7373a760305608a94abb15295 to your computer and use it in GitHub Desktop.
Save itarato/80e29ab7373a760305608a94abb15295 to your computer and use it in GitHub Desktop.
Poorman's Ruby Spy
class Foo
def bar(val, key:)
puts("BAR #{val} #{key}")
end
end
def spy_on(object, method)
did_call = false
aliased = "#{method}_spied".to_sym
object.class.instance_eval do
alias_method aliased, method
end
object.instance_eval do
self.class.define_method(method) do |*args, **kwargs|
did_call = true
send(aliased, *args, **kwargs)
end
end
yield
raise unless did_call
end
foo = Foo.new
spy_on(foo, :bar) do
foo.bar(42, key: "real")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment