public

a quick and dirty example of how to stub a method on an object

  • Download Gist
a simple method stubbing example.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
require 'singleton'
 
class BlockTest
def test
puts "this is the real method."
yield if block_given?
end
end
 
class Object
def stub_method(method)
Foo::Bar.instance.stub_it(self, method)
end
end
 
module Foo
class Bar
include Singleton
def stub_it(object, method)
object.instance_eval(<<-EOF, __FILE__, __LINE__)
def #{method}
puts "this is a stubbed method."
yield if block_given?
end
EOF
end
end
end
 
bt = BlockTest.new
bt.test { puts "and a block from the real method"}
 
bt.stub_method(:test)
bt.test { puts "and a block from the subbed method"}
 
# output is:
# => this is the real method.
# => and a block from the real method
# => this is a stubbed method.
# => and a block from the stubbed method

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.