diff --git a/busted/init.lua b/busted/init.lua index 0d368128..a9b6baac 100644 --- a/busted/init.lua +++ b/busted/init.lua @@ -19,7 +19,7 @@ local function init(busted) local it = function(element) local parent = busted.context.parent(element) - local finally + local finally_blocks = {} if not block.lazySetup(parent) then -- skip test if any setup failed @@ -29,7 +29,7 @@ local function init(busted) if not element.env then element.env = {} end block.rejectAll(element) - element.env.finally = function(fn) finally = fn end + element.env.finally = function(fn) table.insert(finally_blocks, fn) end element.env.pending = busted.pending local pass, ancestor = block.execAll('before_each', parent, true) @@ -38,9 +38,12 @@ local function init(busted) local status = busted.status('success') if busted.safe_publish('test', { 'test', 'start' }, element, parent) then status:update(busted.safe('it', element.run, element)) - if finally then + if #finally_blocks > 0 then block.reject('pending', element) - status:update(busted.safe('finally', finally, element)) + for i = #finally_blocks, 1, -1 do + local finally = finally_blocks[i] + status:update(busted.safe('finally', finally, element)) + end end else status = busted.status('error') diff --git a/spec/core_spec.lua b/spec/core_spec.lua index 4498539e..428bf593 100644 --- a/spec/core_spec.lua +++ b/spec/core_spec.lua @@ -229,6 +229,27 @@ describe('finally callback is called in case of success', function() end) end) +describe('multiple finally callbacks', function() + local order = {} + local f1 = spy.new(function() table.insert(order, "f1") end) + local f2 = spy.new(function() table.insert(order, "f2") end) + local f3 = spy.new(function() table.insert(order, "f3") end) + + it('pushes all finally blocks', function() + finally(f1) + finally(f2) + finally(f3) + assert.is_true(true) + end) + + it('ensures all finally blocks were called', function() + assert.spy(f1).was_called(1) + assert.spy(f2).was_called(1) + assert.spy(f3).was_called(1) + assert.are_same({ "f3", "f2", "f1" }, order) + end) +end) + describe('tests environment', function() global = 'global' --luacheck: ignore