A fixture-free test framework.
local T = require 'knife.test'
Create a test case section.
-
string label
Label for the test case section.
-
function section (T)
Function containing the body of the section. Should define a single parameter
T
which shadows the outerT
, providing the same API.
T('Given a value of 1', function (T)
local value = 1
T('When incremented by 1', function (T)
value = value + 1
-- assertion goes here
end)
end)
Assert that value
is truthy.
-
mixed value
A value (generally the result of an expression) that should be truthy. If the value is
nil
orfalse
, the test fails, otherwise it passes. -
string label
Label for the assertion.
T:assert(value == 2, 'Then the value is equal to 2')
Assert that func
throws an error when invoked.
-
function func
A function that should throw an error when invoked. If the function throws an error, the test passes, otherwise it fails.
-
string label
Label for the assertion.
T:error(function () error 'oops' end,
'Then an error is thrown')
-
The power of this test framework comes from its isolated sections. When executing a test, the entire test is executed from the root section for each leaf section. This makes fixtures unnecessary, as each section serves to initialize state for inner sections. This is best illustrated by example:
T('Given a value of 1', function (T) local value = 1 T('When incremented by 1', function (T) assert(value == 1) value = value + 1 T:assert(value == 2, 'Then the value is equal to 2') end) T('When incremented by 2', function (T) assert(value == 1) -- value is 1 again here! value = value + 2 T:assert(value == 3, 'Then the value is equal to 3') end) end)
-
The module may be run from the command line.
lua knife/test.lua spec/foo.lua spec/bar.lua
When run from the command line,
T
is exported into the global environment.