Skip to content

Instantly share code, notes, and snippets.

@swanson
Created January 28, 2012 02:42
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 swanson/1692237 to your computer and use it in GitHub Desktop.
Save swanson/1692237 to your computer and use it in GitHub Desktop.
Toy stub framework with Ruby
# Playing around with a Toy Stubbing "framework"
class Statistics
def initialize(nums)
@nums = nums
end
def compute_average
sum = 0;
@nums.each do |num|
sum += num
end
sum.to_f / @nums.length
end
end
class StubbedStats < Statistics
methods_to_stub = (instance_methods - Object.instance_methods)
methods_to_stub.each { |m| undef_method m unless m =~ /(^__|^send$|^object_id$)/ }
def initialize(*args)
@canned_responses = {}
end
def method_missing(m, *args, &block)
if @canned_responses.has_key?(m)
@canned_responses[m]
else
raise "Unstubbed method!"
end
end
def canned(m, ret)
@canned_responses[m] = ret
end
end
s = StubbedStats.new
# s.is_a? Statistics => true
s.canned(:compute_average, 6.5)
p "The average is: #{s.compute_average}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment