Pattern 3: Test-Driven Development

Let AI Write the Tests, Then Code to the Spec

Overview

Test Driven Development (TDD) is a variant of plan first development. For some types of tasks, defining a suite of tests is a great way to create a spec. It does not work universally, but it can be particularly effective with the help of AI.

Traditional TDD: write a test, watch it fail, make it pass, refactor.

AI-TDD: Describe the behavior you want, let AI write the test suite, then code until every test passes.

Why bother?

  • Coverage you’d never write. AI generates dozens of edge cases—Unicode, leap seconds, country code +247—while you’re still drinking coffee.
  • Living spec. The test file is the contract; green means done.
  • Early bug detection. Requirement gaps surface before code exists.
  • Mental offload. Focus on algorithms, not edge cases.

This pattern works best for algorithmic code, data transforms, and REST endpoints.

Key Principles

  1. Tests are the specification
  2. Red → green → refactor
  3. Let AI find edge cases
  4. Add tests when you discover gaps

Exercise: Phone Number Parser

Build an international phone parser. Sounds trivial until you remember country codes, extensions, parentheses, spaces, dots, and that 911 is valid but 9-1-1 isn’t.

Steps:

  1. Define requirements “Support E.164, national formats for US/UK/DE/BR, optional extension ‘ext. 123’, reject emergency codes, allow ‘+’, space, dash, dot, parentheses.”

  2. Generate tests Ask AI for complete tests: valid, invalid, malformed, unicode, empty, null, 50+ countries, extensions, leading zeros. Review the list. Delete bad cases. The rest is your spec.

  3. Code to pass Run tests. They’ll fail. Pick the first failure, ask make a minimal fix (or ask AI to), run again. Repeat until green, then refactor.

Your Turn

Pick a project:

  • Username validator: no profanity, no leading digits, max 20 chars
  • Recipe parser: “2 cups flour, sifted” → {amount: 2, unit: 'cups', ingredient: 'flour', note: 'sifted'}
  • Markdown link checker: scan docs, report broken links

Describe the behavior, let AI draft tests, don’t code until tests fail.