Skip to content

Instantly share code, notes, and snippets.

@JoshTGreenwood
Created October 18, 2016 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshTGreenwood/c2445d07841d126d84f0549a71d11e67 to your computer and use it in GitHub Desktop.
Save JoshTGreenwood/c2445d07841d126d84f0549a71d11e67 to your computer and use it in GitHub Desktop.
the beginning of what testdouble.rb might look like
class TestDouble
attr_accessor :instance, :when_stack
def initialize(instance)
@instance = instance
@when_stack = []
end
def when(&block)
fake_method_call = FakeMethodCall.new(block)
if instance.respond_to?(fake_method_call.method_name) # also check arity
add_to_when_stack(block)
else
raise StandardError.new("you tried calling #{fake_method_call.method_name} but your instance doesn't respond to that. Use when! if that is intentional")
end
end
def when!(&block)
add_to_when_stack(block)
end
private
def add_to_when_stack(&block)
fake_method_call = FakeMethodCall.new(block)
@when_stack << fake_method_call
fake_method_call
end
def method_missing(m, *args, &blk)
if stubbed_method = @when_stack.find {|when_stack_item| when_stack_item.method_name == m && when_stack_item.method_args == args}
stubbed_method.return_value
else
super
end
end
end
class FakeMethodCall
attr_accessor :method_name, :method_args, :return_value
def initialize(block)
instance_eval(&block)
end
def then_return(return_value)
@return_value = return_value
end
def method_missing(m, *args, &blk)
@method_name, @method_args = m, args
end
end
class MyClass
def do_something
end
# THIS IS THE API
my_class_test_double = TestDouble.new(MyClass.new)
my_class_test_double.when{do_something(23)}.then_return('Josh')
puts my_class_test_double.do_something(23)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment