lunarmodules / busted

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

Private section in the documentation not accurate #560

Closed bonidjukic closed 7 years ago

bonidjukic commented 7 years ago

I ran into issues while trying to test private functions as per the documentation:

local mymodule = require("mymodule")

describe("Going to test a private element", function()

  setup(function()
    _G._TEST = true
  end)

  teardown(function()
    _G._TEST = nil
  end)

  it("tests the length of the table", function()
    assert.is.equal(#mymodule._private_element, 3)
  end)

end)

Requiring mymodule at the top level executes the code from the module at that instance, so when later we define _G._TEST = true within the setup function, mymodule has already been required and the global _TEST is not set.

I don't see any other way than to declare the mymodule at the top, and then require it within the setup function once the global _TEST has been set:

local mymodule

describe("Going to test a private element", function()

  setup(function()
    _G._TEST = true
    mymodule = require("mymodule")
  end)

  teardown(function()
    _G._TEST = nil
  end)

  it("tests the length of the table", function()
    assert.is.equal(#mymodule._private_element, 3)
  end)

end)
DorianGray commented 7 years ago

The way you are doing it there is correct. Docs were out of date. Would you mind making a PR to update them?

DorianGray commented 7 years ago

I'd do it myself, but I'd like you to be credited with the contribution

bonidjukic commented 7 years ago

@DorianGray, of course, thanks for that! I've created a PR.