Skip to content

Instantly share code, notes, and snippets.

@ggilder
Created January 17, 2012 23:05
Show Gist options
  • Save ggilder/1629653 to your computer and use it in GitHub Desktop.
Save ggilder/1629653 to your computer and use it in GitHub Desktop.
Stub class or instance methods on anything!
class Object
def metaclass
class << self; self; end
end
def self.stub_method_chain chain, &blk
chain = chain.split('.') if chain.is_a? String
metaclass.instance_eval do
define_method chain.first do |*values|
Object.new.tap do |o|
o.stub_method_chain chain.slice(1..-1), &blk
end
end
end
end
def stub_method_chain chain, &blk
chain = chain.split('.') if chain.is_a? String
metaclass.instance_eval do
define_method chain.first do |*values|
if chain.size == 1
blk.call *values
else
Object.new.tap do |o|
o.stub_method_chain chain.slice(1..-1), &blk
end
end
end
end
end
end
require 'minitest/autorun'
describe "stub method chain" do
describe "class method" do
before do
@klass = Class.new
@klass.stub_method_chain("foo.bar.baz") {|*args| "hi there!"}
end
it "stubs a chain of methods on a class" do
@klass.foo.bar.baz.must_equal "hi there!"
end
end
describe "instance method" do
before do
@obj = Object.new
@obj.stub_method_chain("qux.qar.qi") {|*args| "hello!"}
end
it "stubs a chain of methods on an object" do
@obj.qux.qar.qi.must_equal "hello!"
end
end
end
@armandocanals
Copy link

beast

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment