Navigation Menu

Skip to content

Commit

Permalink
Allow a stub to return a specific value
Browse files Browse the repository at this point in the history
  • Loading branch information
Damian Galarza committed Mar 5, 2015
1 parent 0f3cb78 commit afba639
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 6 additions & 0 deletions spec/stub_spec.lua
Expand Up @@ -92,4 +92,10 @@ describe("Tests dealing with stubs", function()
assert.is_nil(s)
end)

it("returns a given return value", function()
stub(test, "key", "foo")

assert.is.equal("foo", test.key())
end)

end)
6 changes: 4 additions & 2 deletions src/stub.lua
Expand Up @@ -2,10 +2,9 @@
local assert = require 'luassert.assert'
local spy = require 'luassert.spy'
local util = require 'luassert.util'
local stubfunc = function() end
local stub = {}

function stub.new(object, key)
function stub.new(object, key, return_value)
if object == nil and key == nil then
-- called without arguments, create a 'blank' stub
object = {}
Expand All @@ -14,6 +13,9 @@ function stub.new(object, key)
assert(type(object) == "table" and key ~= nil, "stub.new(): Can only create stub on a table key, call with 2 params; table, key")
assert(object[key] == nil or util.callable(object[key]), "stub.new(): The element for which to create a stub must either be callable, or be nil")
local old_elem = object[key] -- keep existing element (might be nil!)
local stubfunc = function()
return return_value
end
object[key] = stubfunc -- set the stubfunction
local s = spy.on(object, key) -- create a spy on top of the stub function
local spy_revert = s.revert -- keep created revert function
Expand Down

0 comments on commit afba639

Please sign in to comment.