Skip to content

Instantly share code, notes, and snippets.

@thermistor
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thermistor/8f55ee442e343579d27a to your computer and use it in GitHub Desktop.
Save thermistor/8f55ee442e343579d27a to your computer and use it in GitHub Desktop.
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