← Lua Academy

Test-driven development · 46 / 69

Share deterministic setup

YOUR TASK

Make this happen

3 steps
  1. before_each prepares a case without coupling it to another case’s state. The cache mock is reinstalled for every test. Implement a reader that forwards its key and respects the success flag.

  2. Read the cases in lesson.test.lua, then choose Check solution to see what needs to change.

  3. Update subject.lua until every test passes. Keep the supplied tests unchanged.

Read the starter and tests

subject.lua

exports.read = function(key: string)
  return "fixed"
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.describe("reader", function()
  t.before_each(function()
    t.mock.host("ctx.cache.get"):using(function(key)
      return true, "value:" .. key
    end)
  end)
  t.it("first key", function()
    t.expect(subject.load().read("a")):eq("value:a")
  end)
  t.it("second key", function()
    t.expect(subject.load().read("b")):eq("value:b")
  end)
end)