Skip to content

// Testing · 05

Test-Driven Development

Red: test failsleads tokeep greenGreen: passesleads toRefactor

Write the smallest failing test, make it pass, then tidy up.

How it fits together

Test-Driven Development structureRed: test failsone new behaviourrun it, watch it failRefactor (green)rename, extracttests stay greenGreen: all passsimplest codea constant is fine2 make it pass3 tidy up4 next test
uses / calls· numbered steps replay in order
  • Red: test fails uses / calls Green: all pass (2 make it pass)
  • Green: all pass uses / calls Refactor (green) (3 tidy up)
  • Refactor (green) uses / calls Red: test fails (4 next test)

Spot it

  • Unsure what the next change should be
  • Code written before any test that checks it
  • Refactors break things nobody notices

It costs

Slower first hours, and tests that must be kept honest; design problems show early.

Go deeperThe full explanation and what to ask for · 1 min readExpand

The cycle has three steps. Red: write one test for the next behaviour and watch it fail, which shows the test can fail at all. Green: write the least code that passes, even if it is ugly; returning a constant is a valid step. Refactor: clean up names and structure with the tests as the safety net, and only while they are green.

Triangulation handles a shortcut. When one example can be met by a hard-coded answer, add a second example with a different input to force the general rule. Pick the smallest failing test, not the most complete one, because the goal is to learn what the next step is.

Work in vertical slices: one behaviour through every layer, not all of one layer at a time. A tracer bullet is a thin slice that touches each layer and proves the path works end to end. Horizontal layers hide design errors until everything is wired up. When NOT to: throwaway spikes to learn an unfamiliar library or UI do not need the cycle until the shape is clear.

Ask for it

  • red
  • green
  • refactor
  • triangulation
  • fake it
  • vertical slice

Build the discount rule test-first, one slice at a time: first a test that a 10% code on 100.00 gives 90.00 (red), then the simplest code to pass (green). Add a second amount to force the real formula, then refactor. Each cycle ends with the whole suite green.