Skip to content

Testing & QA

TDD: Red → Green → Refactor

The idea, in plain English

Test-Driven Development (TDD) flips the usual order: you write the test BEFORE the code. It's like writing the answer key before the exam, then filling in the exam until it scores full marks. First you write a test and watch it fail because the feature doesn't exist yet — that's RED. Then you write the simplest code that makes it pass — that's GREEN. Then you tidy the code up without breaking the test — that's REFACTOR. Repeat in tiny loops.

How it works

  1. 1RED: write a test for behavior that doesn't exist yet, and run it. It fails — proving the test actually checks something.
  2. 2GREEN: write the smallest amount of real code needed to make that test pass. Don't gold-plate.
  3. 3REFACTOR: clean up names and structure now that the test guards you. The test must still pass afterward.
  4. 4Loop back to RED for the next small piece of behavior. Each cycle is minutes, not hours.

When you'd use it

TDD shines on logic with clear right-and-wrong answers — parsers, calculations, rules engines — where you can state the expected result up front. It's less natural for exploratory UI work, where you're still figuring out what you even want.

Common beginner mistakes

  • Skipping the RED step. If you never saw the test fail, you don't actually know it can catch the bug — it might pass no matter what.
  • Writing far more code than the test demands in the GREEN step. Add just enough to pass; let the next failing test drive the next bit of code.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
RED   (stub):    FAIL
GREEN (built):   PASS
GREEN (built):   PASS

Not sure this is the right topic? See the learning paths → or where this leads →