Test-driven development (TDD) flips the usual order of work: you write a failing test for the behaviour you want, then write just enough code to make it pass. Every line of code exists because a test asked for it.
The red, green, refactor cycle
TDD works in short loops, often only a few minutes each:
- Red: write one small test for behaviour that doesn't exist yet, and run it. It should fail. A test that passes before you've written the code isn't checking anything new.
- Green: write the simplest code that makes the test pass. Don't add anything the test doesn't ask for.
- Refactor: with the test passing, tidy the code, for example by renaming things or removing duplication. Run the tests again to check nothing broke.
Then pick the next small behaviour and go round again.
A small example
Say you need a function that adds 20% VAT to a price. Start with the test, written for pytest:
from pricing import add_vat
def test_adds_twenty_percent():
assert add_vat(100) == 120Running it fails, because add_vat doesn't exist yet. That's red. Now write the smallest code that passes:
Wondering how this was made? How we make these