Skip to content

Instantly share code, notes, and snippets.

@zamith
Last active August 29, 2015 14:14
Show Gist options
  • Save zamith/81ceb704ec3e1e3efd09 to your computer and use it in GitHub Desktop.
Save zamith/81ceb704ec3e1e3efd09 to your computer and use it in GitHub Desktop.
require "spec"
class Double
def initialize(@name, @stubs = {} of Symbol => Object)
end
def receives_and_returns(method_name = :none, return_value = true)
stubs[method_name] = return_value
end
macro method_missing(name, args, block)
if stubs.try &.[:{{name}}]?
stubs[:{{name}}]
else
fail "Double \"#{name}\" received unexpected message :#{{{name}}}"
end
end
private getter :name, :stubs, :current_stub_name
end
describe "Mocks" do
it "tests a double" do
d = Double.new("Double", { hello: "Hello World" })
d.hello.should eq "Hello World"
end
it "can be added stubs after initialization" do
d = Double.new("Double")
d.receives_and_returns(method_name: :hello, return_value: 123)
d.hello.should eq 123
end
end
@zamith
Copy link
Author

zamith commented Feb 4, 2015

I would like to have a hash where the keys are symbols, but how do I compare that to {{name}}, if there is no to_sym?

Also, I don't like to have to declare the Value type, any way around it?

@asterite
Copy link

asterite commented Feb 4, 2015

  1. if stubs.has_key?(:{{name}}) (note the colon)
  2. {} of String => _

@asterite
Copy link

asterite commented Feb 4, 2015

No, 2 is wrong. Why not @stubs = nil and then @stubs.try &.[key]?

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