Add method to define stubs

This commit is contained in:
Michael Miller 2022-03-12 14:31:19 -07:00
parent 123dd0efca
commit ea46af00a6
No known key found for this signature in database
GPG key ID: 32B47AE8F388A1FF
3 changed files with 42 additions and 1 deletions

View file

@ -209,4 +209,41 @@ Spectator.describe Spectator::Double do
end
end
end
describe "#_spectator_define_stub" do
subject(dbl) { FooBarDouble.new }
let(stub3) { Spectator::ValueStub.new(:foo, 3) }
let(stub5) { Spectator::ValueStub.new(:foo, 5) }
let(stub7) { Spectator::ValueStub.new(:foo, 7, Spectator::Arguments.capture(:lucky)) }
it "overrides an existing method" do
expect { dbl._spectator_define_stub(stub3) }.to change { dbl.foo }.from(42).to(3)
end
it "replaces an existing stub" do
dbl._spectator_define_stub(stub3)
expect { dbl._spectator_define_stub(stub5) }.to change { dbl.foo }.from(3).to(5)
end
it "doesn't affect other methods" do
expect { dbl._spectator_define_stub(stub5) }.to_not change { dbl.bar }
end
it "picks the correct stub based on arguments" do
dbl._spectator_define_stub(stub5)
dbl._spectator_define_stub(stub7)
aggregate_failures do
expect(dbl.foo).to eq(5)
expect(dbl.foo(:lucky)).to eq(7)
end
end
it "only uses a stub if an argument constraint is met" do
dbl._spectator_define_stub(stub7)
aggregate_failures do
expect(dbl.foo).to eq(42)
expect(dbl.foo(:lucky)).to eq(7)
end
end
end
end

View file

@ -9,6 +9,6 @@ module Spectator
module DSL
# Keywords that cannot be used in specs using the DSL.
# These are either problematic or reserved for internal use.
RESERVED_KEYWORDS = %i[initialize _spectator_stubbed_name _spectator_find_stub]
RESERVED_KEYWORDS = %i[initialize _spectator_stubbed_name _spectator_find_stub _spectator_define_stub]
end
end

View file

@ -37,6 +37,10 @@ module Spectator
def initialize(@stubs : Array(Stub) = [] of Stub)
end
protected def _spectator_define_stub(stub : Stub) : Nil
@stubs.unshift(stub)
end
private def _spectator_find_stub(call) : Stub?
Log.debug { "Finding stub for #{call}" }
stub = @stubs.find &.===(call)