Discussions
Explain TDD with Real-World Examples: How to Write Your First Red-Green-Refactor Cycle
When teams ask people to explain TDD, many overcomplicate it with theory — but in reality, TDD is one of the simplest mental models in software development. It’s just about flipping the order of work: tests first, code next. The elegance comes from the loop itself — Red → Green → Refactor.
Let’s break down the cycle using a small, real-world example.
Imagine you’re building a small utility function: calculateDiscount() for an e-commerce checkout page. In traditional coding, most developers would just start writing code and then test manually. In TDD, you begin by writing a failing test.
RED:
Write a test for what you expect — e.g., 10% discount applied to $100 should return $90. The test fails (good — it should). Now you have a clearly defined expected behavior.
GREEN:
Write the simplest implementation possible that returns $90 for that case. Don’t optimize — just get it passing.
REFACTOR:
Now improve the logic — handle different percentages, variable prices, edge cases — while making sure the test keeps passing. If it breaks, the test catches you instantly.
In other words: define correctness → create code → improve gradually.
This workflow scales — from tiny functions to APIs and microservices. And modern tooling makes it smoother than ever. For example, platforms like Keploy can auto-generate real API test cases from traffic — meaning you can combine TDD + captured real workflows without manually writing every scenario yourself.
