Add mock registry fetch method

Solves the issue of pre-populating a mock with stubs.
This commit is contained in:
Michael Miller 2022-05-15 00:36:29 -06:00
parent 7923eb3ad0
commit 86b49dc20e
No known key found for this signature in database
GPG key ID: AC78B32D30CE34A2
3 changed files with 41 additions and 4 deletions

View file

@ -59,7 +59,15 @@ module Spectator
{% end %}
private def _spectator_stubs
@@_spectator_mock_registry[self]
@@_spectator_mock_registry.fetch(self) do
{% begin %}
[
{% for key, value in value_methods %}
::Spectator::ValueStub.new({{key.id.symbolize}}, {{value}}),
{% end %}
] of ::Spectator::Stub
{% end %}
end
end
# Returns the mock's name formatted for user output.

View file

@ -23,5 +23,16 @@ module Spectator
key = Box.box(object)
@object_stubs[key]
end
# Retrieves all stubs defined for a mocked object.
#
# Yields to the block on the first retrieval.
# This allows a mock to populate the registry with initial stubs.
def fetch(object : Reference, & : -> Array(Stub))
key = Box.box(object)
@object_stubs.fetch(key) do
@object_stubs[key] = yield
end
end
end
end