Skip to content

Instantly share code, notes, and snippets.

@thermistor thermistor/perfect_mock.rb
Last active Aug 29, 2015

Embed
What would you like to do?
A perfect ruby mock
# from http://taylor.fausak.me/2014/05/24/class-comparison-in-ruby/
require 'forwardable'
def fake(klass)
Class.new(BasicObject) do
eigenclass = class << self; self end
eigenclass.extend Forwardable
eigenclass.def_delegators klass, *%i[
<
<=
<=>
==
===
>
>=
__id__
ancestors
eql?
equal?
inspect
name
object_id
to_s
]
define_method :class do
klass
end
define_method :inspect do
"#<#{klass.name}:0x#{'%x' % (__id__ << 1)}>"
end
alias_method :to_s, :inspect
define_method :instance_of? do |other|
klass == other
end
define_method :is_a? do |other|
klass >= other
end
alias_method :kind_of?, :is_a?
end
end
# Usage
# FakeCheese = fake(Cheese)
# # => Cheese
# american = FakeCheese.new
# # => #<Cheese:0x7fd8e1e5ba48>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.