Support creating instances of mocked modules via class

This is a bit of a hack.
The `.new` method is added to the module, which creates an instance that includes the mocked module.
No changes to the def_mock and new_mock methods are necessary.

For some reason, infinite recursion occurs when calling `.new` on the class.
To get around the issue for now, the internal method of allocation is used.
That is, allocate + initialize.
This commit is contained in:
Michael Miller 2022-12-18 16:04:49 -07:00
parent d378583054
commit fa99987780
No known key found for this signature in database
GPG key ID: 32B47AE8F388A1FF
4 changed files with 388 additions and 0 deletions

View file

@ -39,6 +39,29 @@ module Spectator
{% if base.id == :module.id %}
{{base.id}} {{type_name.id}}
include {{mocked_type.id}}
# Mock class that includes the mocked module {{mocked_type.id}}
{% if name %}@[::Spectator::StubbedName({{name}})]{% end %}
private class ClassIncludingMock{{type_name.id}}
include {{type_name.id}}
end
# Returns a mock class that includes the mocked module {{mocked_type.id}}.
def self.new(*args, **kwargs) : ClassIncludingMock{{type_name.id}}
# FIXME: Creating the instance normally with `.new` causing infinite recursion.
inst = ClassIncludingMock{{type_name.id}}.allocate
inst.initialize(*args, **kwargs)
inst
end
# Returns a mock class that includes the mocked module {{mocked_type.id}}.
def self.new(*args, **kwargs) : ClassIncludingMock{{type_name.id}}
# FIXME: Creating the instance normally with `.new` causing infinite recursion.
inst = ClassIncludingMock{{type_name.id}}.allocate
inst.initialize(*args, **kwargs) { |*yargs| yield *yargs }
inst
end
{% else %}
{{base.id}} {{type_name.id}} < {{mocked_type.id}}
{% end %}