Skip to content

Instantly share code, notes, and snippets.

@jah2488
Created October 9, 2012 01:47
Show Gist options
  • Select an option

  • Save jah2488/3856102 to your computer and use it in GitHub Desktop.

Select an option

Save jah2488/3856102 to your computer and use it in GitHub Desktop.
Quick and Dirty "Mock" and "Stub" functionality in ruby. Could be used for making Independent mock files or for NullObjects
require 'rubygems'
require 'rspec'
module FakeIt
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def mocks(class_name)
class_name.instance_methods(false).map { |method_name| define_method(method_name) { |*args| } }
class_name.methods(false).map { |method_name| define_singleton_method(method_name) { |*args| } }
end
def will_stub(method_name, &block)
raise "Method Isn't Defined on Base Class" unless method_defined?(method_name)
define_method(method_name) { |*args| yield }
end
end
end
# TEST CLASS
class MyNode
def hello
"hi"
end
def johnny
"bill"
end
def add(first, second)
first + second
end
def self.used
"u called me"
end
end
class MyFakeNode
include FakeIt
mocks MyNode
will_stub(:add) { "five" }
end
mfn = MyFakeNode.new
MyFakeNode.used #=> "u called me"
mfn.hello #=> nil (No error is thrown however)
mfn.add #=> "five"
mfn.add 2, 3 #=> "five"
mfn.subtract #=> NoMethodError
describe FakeIt do
it "mocks all methods on fake class" do
MyFakeNode.instance_methods(false).should == MyNode.instance_methods(false)
end
it "mocks all class methods on fake class" do
MyFakeNode.methods(false).should == MyNode.methods(false)
end
it "returns the stubbed response for a given methods" do
a = MyFakeNode.new
a.add.should == "five"
end
it "should raise exception if method is not defined on base class" do
lambda {
a = class MyFake
include FakeIt
mocks MyNode
will_stub(:subtract) { "10"}
end
}.should raise_error
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment