Course contentsShow
← Software Engineering
Lesson 489 of 1,93315. Test-Driven DevelopmentFree lesson

Red: Writing the Failing Test First

Understand why writing the test before implementation forces clear requirements and testable design.

Red: Writing the Failing Test First

What you'll learn: Why deliberately writing a test that fails first leads to clearer requirements and more testable code.


In Test-Driven Development's Red-Green-Refactor loop, "Red" means writing a test for functionality that doesn't exist yet. You run the test, watch it fail (turn "red"), and only then write the code to make it pass.

This feels backward at first—why write a test for something you haven't built? But this constraint is incredibly powerful.

Why Red Comes First

It forces you to define requirements before implementation. When you write the test first, you must decide:

  • What should this function be called?
  • What inputs does it need?
  • What output should it produce?
  • How should edge cases behave?

You can't be vague. The test is your specification, written in executable code.

It guarantees your code is testable. If you write code first, you might create something that's difficult or impossible to test—tangled dependencies, hidden state, or unclear interfaces. Writing the test first means your design must support testing from the beginning.

It proves your test actually works. A test that never fails might be broken or might not test what you think. Seeing it fail first confirms it's actually checking the right thing.

A Simple Example

Instead of jumping straight to implementation, you write:

// First: Write the test (no implementation exists yet)
assert(add(2, 3) === 5);

This fails because add doesn't exist. Now you know exactly what to build.

Key Takeaway: Writing the failing test first transforms vague ideas into concrete requirements, ensures testability from the start, and proves your test can actually detect problems.