TDD Is a Design Tool, Not a Testing Tool

Take a typical case, made up for illustration. A developer added a rule to a promotion engine, “vouchers cannot stack with buy-two-get-one”, and tested the new case thoroughly. Three other promotions relied on the old stacking order, which no test described. They gave wrong discounts all weekend.

Tests written after the code tend to check what the code does. Tests written first check what it should do, one small example at a time. Below is the red-green-refactor cycle, triangulation, outside-in and inside-out styles, BDD, working with legacy code, and an honest list of what TDD will not do for you.

If tests always come after the code
  • You write tests after the code, just before the PR
  • Your classes have private methods you wish you could test directly
  • Refactoring feels dangerous because nothing pins down behavior
  • Test names describe what the code does (“callsRepoFindByIdOnce”) not what it should do

A short Red, Green, Refactor cycle, a few minutes at most per step, becomes a habit with practice and changes how you write code.

The Cycle


flowchart LR
    R[🔴 Red<br/>write a failing test] --> G[🟢 Green<br/>simplest code to pass]
    G --> RF[🔵 Refactor<br/>improve design, tests still green]
    RF --> R
      
  1. Red. Write a test that describes the next small behavior. Run it. Watch it fail for the right reason (not a typo, an actual missing behavior).
  2. Green. Write the simplest code that makes the test pass. Hardcode if you have to. Don't solve future tests.
  3. Refactor. Improve names, eliminate duplication, simplify shapes. Tests stay green throughout.

Triangulation — When To Generalize

The rule of thumb: don't generalize from one example. With one test, hardcode. With two, you might see a pattern. With three, refactor to the general case. This keeps you from writing speculative abstractions.

// Test 1
it('sums one number', () => expect(sum([1])).toBe(1));
// Implementation: function sum(xs) { return 1; } ← hardcode!

// Test 2
it('sums two numbers', () => expect(sum([1, 2])).toBe(3));
// Now you must generalize
function sum(xs: number[]) { return xs[0] + (xs[1] ?? 0); }

// Test 3
it('sums many numbers', () => expect(sum([1, 2, 3])).toBe(6));
// Pattern is obvious; refactor
function sum(xs: number[]) { return xs.reduce((a, b) => a + b, 0); }

Outside-In TDD (London School)

Start at the system boundary — an HTTP endpoint, a UI action — and write a test that describes what the user wants. Use mocks for the collaborators that don't exist yet; each mock becomes a TODO list for the next layer down. Drive the system from the outside in, creating components only when a higher-level test demands them.

Inside-Out TDD (Chicago / Classicist School)

Start at a leaf domain object. Build it bottom-up with no mocks — real collaborators all the way down. The two styles aren't opposed; a common mix is outside-in for new features and inside-out for pure domain logic.

BDD — Same Cycle, Different Vocabulary

Behavior-Driven Development reframes “test” as “behavior example” and uses Given/When/Then to align with product language. Whether you adopt Gherkin and Cucumber depends on whether your product folks actually write the scenarios. If only developers write them, plain RSpec/xUnit with descriptive names is simpler.

describe('Cart', () => {
  describe('when adding an item already in the cart', () => {
    it('increments its quantity instead of adding a duplicate row', () => {
      const cart = aCart().with({ sku: 'X', qty: 1 }).build();
      cart.add({ sku: 'X', qty: 2 });
      expect(cart.lines).toEqual([{ sku: 'X', qty: 3 }]);
    });
  });
});

Working With Legacy Code (Feathers)

TDD on a greenfield is easy. The real test is a 12-year-old codebase with 4% coverage. Michael Feathers' Working Effectively with Legacy Code gives you the moves:

  1. Characterization tests — pin down current behavior, even if it's weird. Don't fix bugs, just record what is.
  2. Sprout method / sprout class — write new behavior in a small testable unit; call it from the legacy code.
  3. Seams — find points where you can change behavior without editing in-place (constructor injection, parameterized statics).
  4. Extract and override — pull dependencies into virtual methods so a test subclass can stub them.

What TDD Won't Do

  • It won't teach you architecture. You still need to know “a controller shouldn't talk to a DB driver”.
  • Unit-level TDD won't catch integration bugs. TDD is a way of working, not a test level, so let integration and acceptance tests drive that work too.
  • It won't make a 200-line method good. TDD reveals the smell; you still need the courage to break the method up.
  • It won't replace design discussions — for complex domains, time at the whiteboard before TDD can save a lot of refactoring.

Common Pushbacks and Honest Answers

ObjectionReality
“TDD is slower”Often slower at first. It can pay back through fewer rework cycles and less time in the debugger, so measure it on your own team.
“I don't know what to test first”Start with the smallest observable behavior. Often the happy path with one input.
“UI / frontend isn't suitable for TDD”Component tests with Testing Library cover most of it. E2E for what they can't.
“Our domain is too complex”That's the case where TDD pays off the most. Examples force the ambiguity into the open.

A Sample Session

// RED — describe one tiny behavior
it('returns "FizzBuzz" for 15', () => {
  expect(fizzbuzz(15)).toBe('FizzBuzz');
});

// GREEN — simplest thing that works (yes, really)
// (Each stage here replaces the last one. They're successive edits, not one file.)
const fizzbuzz = (n: number) => 'FizzBuzz';

// RED — drive out the next case
it('returns "Fizz" for 3', () => {
  expect(fizzbuzz(3)).toBe('Fizz');
});

// GREEN
const fizzbuzz = (n: number) => n === 3 ? 'Fizz' : 'FizzBuzz';

// RED
it('returns "Buzz" for 5', () => { ... });

// ... after enough tests, the pattern emerges; refactor
const fizzbuzz = (n: number) => {
  if (n % 15 === 0) return 'FizzBuzz';
  if (n % 3 === 0)  return 'Fizz';
  if (n % 5 === 0)  return 'Buzz';
  return String(n);
};

Pitfalls

Skipping the Refactor step

Without refactor, the code grows messy and the tests grow brittle around it. Refactor isn't optional — it's where TDD's design benefit actually happens.

Writing the test after the code “in your head”

If you already know the implementation, the test ends up shaped around it (coupled to private internals). Force yourself to start with the test and let the implementation surprise you.

Mock-heavy outside-in TDD without rolling down

Outside-in TDD creates mocks at every layer; each mock is a debt you owe to the next layer's real implementation. If you never roll down, you have a beautifully tested top layer over an untested mess.

TDD With a Coding Agent

TDD has found a second life with coding agents. A failing test is the clearest instruction you can give: it's unambiguous, it's checkable, and the agent can iterate until it passes. Write the test first, or have the agent write it, and confirm that it fails for the right reason. Then let the agent make it pass, and don't let it edit the test.

The discipline that matters is keeping the test and the implementation apart. If a single session writes both, the test tends to fit the code. Review the test yourself before any code exists. That's where your judgment goes. The red-green-refactor rhythm is still useful, because each passing step gives you a commit to return to, and the agent's mistakes stay small and easy to revert.