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