I have a Lua function that returns false
followed by error message and want to test its behavior using the busted testing framework. Right now I am doing it a bit like this:
function safe_divide(a, b)
if b > 0 then -- buggy! should be b ~= 0
return a / b
else
return false, "division by zero"
end
end
describe("safe_divide", function()
it("can divide by positive numbers", function()
local ok, err = safe_divide(10.0, 5.0)
assert.truthy(ok)
assert.are.same(2.0, ok)
end)
it("errors when dividing by zero", function()
local ok, err = safe_divide(10.0, 0.0)
assert.not_truthy(ok)
assert.are.same("division by zero", err)
end)
it("can divide by negative numbers", function()
local ok, err = safe_divide(-10.0, -5.0)
assert.truthy(ok)
assert.are.same(2.0, ok)
end)
end)
There are two things that I don't like about my current approach:
- Each test is 3 lines instead of a single clean line
- When the 3rd test fails, busted just says that
false
is not a truthy value as expected, and never mentions the "divide by zero" error message.
Is there a way I can improve my test file to avoid these problems?
I think what I want to do is kind of similar to the has_error
assertion in busted but that seems to be only for functions that actually raise exceptions, not for functions that return false
followed by error message.
Busted makes use of luassert, that can be extended with your own assertions.
For instance, the following code uses a user-defined assertion
answers
that takes as first parameter a table of the expected result, and the effective function results as remaining parameters.This code lacks correct formatting for the assertion message. You can look at the
luaassert
documentation, or at the predefined assertions. It contains asay
module for translations of messages.