Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created October 22, 2009 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mxriverlynn/215637 to your computer and use it in GitHub Desktop.
Save mxriverlynn/215637 to your computer and use it in GitHub Desktop.
a quick and dirty example of how to stub a method on an object
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment