diff --git a/lib/sinon/spy.js b/lib/sinon/spy.js index d98ce5556..ebc87f49b 100644 --- a/lib/sinon/spy.js +++ b/lib/sinon/spy.js @@ -53,9 +53,11 @@ function matchingFake(fakes, args, strict) { return undefined; } - for (var i = 0, l = fakes.length; i < l; i++) { - if (fakes[i].matches(args, strict)) { - return fakes[i]; + var fakesIndex = fakes.length; + + while (fakesIndex--) { + if (fakes[fakesIndex].matches(args, strict)) { + return fakes[fakesIndex]; } } diff --git a/test/stub-test.js b/test/stub-test.js index b745df20a..dc0033e85 100644 --- a/test/stub-test.js +++ b/test/stub-test.js @@ -1345,6 +1345,24 @@ describe("stub", function () { assert.equals(stub(), 23); assert.equals(stub({ foo: "bar", bar: "foo" }), 99); }); + + it("ensure stub uses last matching arguments", function () { + var stub = createStub().returns(23); + stub.withArgs(2).returns(9); + stub.withArgs(2).returns(99); + + assert.equals(stub(), 23); + assert.equals(stub(2), 99); + }); + + it("ensure stub uses last matching sinonMatch arguments", function () { + var stub = createStub().returns(23); + stub.withArgs(2).returns(9); + stub.withArgs(sinonMatch(2)).returns(99); + + assert.equals(stub(), 23); + assert.equals(stub(2), 99); + }); }); describe(".callsArgAsync", function () {