Add ValueMockRegistry

Support injecting mock functionality into concrete structs (value types).
This commit is contained in:
Michael Miller 2022-05-15 12:34:50 -06:00
parent 51f133eb61
commit 37c6db250d
No known key found for this signature in database
GPG key ID: 32B47AE8F388A1FF
4 changed files with 153 additions and 0 deletions

View file

@ -16,6 +16,22 @@ class MockedClass
end
end
struct MockedStruct
getter method1 = 42
def method2
:original
end
def method3
"original"
end
def instance_variables
[{{@type.instance_vars.map(&.name.symbolize).splat}}]
end
end
Spectator.describe Spectator::Mock do
describe "#define_subclass" do
class Thing
@ -106,5 +122,43 @@ Spectator.describe Spectator::Mock do
expect(mock.instance_variables).to eq([:method1])
end
end
context "with a struct" do
Spectator::Mock.inject(MockedStruct, :mock_name, method1: 123) do
stub def method2
:stubbed
end
end
let(mock) { MockedStruct.new }
it "overrides responses from methods with keyword arguments" do
expect(mock.method1).to eq(123)
end
it "overrides responses from methods defined in the block" do
expect(mock.method2).to eq(:stubbed)
end
it "allows methods to be stubbed" do
stub1 = Spectator::ValueStub.new(:method1, 777)
stub2 = Spectator::ValueStub.new(:method2, :override)
stub3 = Spectator::ValueStub.new(:method3, "stubbed")
aggregate_failures do
expect { mock._spectator_define_stub(stub1) }.to change { mock.method1 }.to(777)
expect { mock._spectator_define_stub(stub2) }.to change { mock.method2 }.to(:override)
expect { mock._spectator_define_stub(stub3) }.to change { mock.method3 }.from("original").to("stubbed")
end
end
it "doesn't change the size of an instance" do
expect(sizeof(MockedStruct)).to eq(4) # sizeof(Int32)
end
it "doesn't affect instance variables" do
expect(mock.instance_variables).to eq([:method1])
end
end
end
end