Initial code to support anonymous doubles

This commit is contained in:
Michael Miller 2019-11-12 21:55:16 -07:00
parent b0562981f7
commit b9fe1b6a60
3 changed files with 58 additions and 16 deletions

View file

@ -2,6 +2,9 @@ require "../mocks"
module Spectator::DSL
macro double(name, **stubs, &block)
{% if name.is_a?(StringLiteral) %}
anonymous_double({{name}}, {{stubs.double_splat}})
{% else %}
{%
safe_name = name.id.symbolize.gsub(/\W/, "_").id
type_name = "Double#{safe_name}".id
@ -12,6 +15,7 @@ module Spectator::DSL
{% else %}
define_double({{type_name}}, {{name}}, {{stubs.double_splat}}) {{block}}
{% end %}
{% end %}
end
macro create_double(type_name, name, **stubs)
@ -40,7 +44,14 @@ module Spectator::DSL
end
end
def anonymous_double(name : String, **stubs)
Mocks::AnonymousDouble.new(name, stubs)
end
macro null_double(name, **stubs, &block)
{% if name.is_a?(StringLiteral) %}
anonymous_null_double({{name}}, {{stubs.double_splat}})
{% else %}
{%
safe_name = name.id.symbolize.gsub(/\W/, "_").id
type_name = "Double#{safe_name}".id
@ -51,6 +62,7 @@ module Spectator::DSL
{% else %}
define_null_double({{type_name}}, {{name}}, {{stubs.double_splat}}) {{block}}
{% end %}
{% end %}
end
macro create_null_double(type_name, name, **stubs)
@ -79,6 +91,10 @@ module Spectator::DSL
end
end
def anonymous_null_double(name : Strings, **stubs)
AnonymousNullDouble.new(name, stubs)
end
macro mock(name, &block)
{% resolved = name.resolve
type = if resolved < Reference

View file

@ -0,0 +1,16 @@
module Spectator::Mocks
class AnonymousDouble(T)
def initialize(@name : String, @values : T)
end
def as_null_object
AnonymousNullDouble.new(@values)
end
macro method_missing(call)
@values.fetch({{call.name.symbolize}}) do
raise ::Spectator::Mocks::UnexpectedMessageError.new("#{self} received unexpected message {{call.name}}")
end
end
end
end

View file

@ -0,0 +1,10 @@
module Spectator::Mocks
class AnonymousNullDouble(T)
def initialize(@name : String, @values : T)
end
macro method_missing(call)
@values.fetch({{call.name.symbolize}}) { self }
end
end
end