lunarmodules / busted

Elegant Lua unit testing.
https://lunarmodules.github.io/busted/
MIT License
1.4k stars 185 forks source link

How to run a `before_each` function on every test #613

Closed ktalebian closed 4 years ago

ktalebian commented 5 years ago

I run my tests like rusty tests/app/init.lua. For all my tests, I want to have a before_each function that runs on all of my tests. I've been able to do this, but I think this is very hacky:

-- tests/app/init.lua

require 'busted.runner'()

local busted = require 'tests.setup'

busted.describe('init', function()
  describe('a test suite', function() 
     ...
  end)
end)

-- tests/setup.lua 

require 'busted.runner'()
local busted = require('busted')

local mt = getmetatable(busted)
mt.__newindex = nil
local describe = busted.describe

busted.describe = function(title, cb)
    describe(title, function()
        busted.before_each(function()
            -- can run anything here
        end)

        cb()
    end)
end

return busted

Is this going to cause any issues? It seems to work fine. Is there a recommended way of doing this?

Tieske commented 5 years ago

not sure I get the issue you're trying to solve?

are you trying to run a single handler on each test, where the tests are spread over multiple files? and hence independent describe blocks?

How about:

-- tests/app/init.lua

require 'busted.runner'()

busted.describe('init', function()

  require('tests.setup')()  -- inject global before_each handler

  describe('a test suite', function() 
     ...
  end)
end)

-- tests/setup.lua 

return function()
   before_each(function()
     -- run anything here 
   end)
end
piotrp commented 4 years ago

Another possibility:

require("busted").subscribe({"test", "start"}, function() <your code> end)

This can be put in --helper script. I'm using this pattern to run some system tests: I set up my environment in {"suite", "start"} and tear it down in {"suite", "end"}.

Tieske commented 4 years ago

nice example @Crack 👍

Tieske commented 4 years ago

@ktalebian can we close this?

ktalebian commented 4 years ago

Yep.