Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 134 ยท Testing and Tooling

Test-Driven Development

Learn test-driven development in Ruby with Minitest. Follow the red, green, refactor cycle step by step by building a Roman numeral converter test-first.

Most people write the code first and the tests later, if at all. Test-driven development (TDD) flips the order: you write a small failing test, then write just enough code to make it pass, then clean up. Repeat this loop many times and a program grows in tiny, safe steps, each one backed by a test.

TDD is not magic and it is not a religion. It is a technique with real benefits: you design the interface of your code before the details, you only write code that something needs, and you always have a safety net for refactoring. In this lesson you will practice it on a small problem, converting numbers to Roman numerals, using Minitest. Seeing the loop run a few times matters more than any definition.

The cycle: red, green, refactor

  1. Red. Write one small test for behavior that does not exist yet. Run it and watch it fail. A test that has never failed might not be testing anything.
  2. Green. Write the simplest code that makes the test pass. Quick and even silly is fine at this point.
  3. Refactor. With the tests green, improve the code: remove duplication, rename things, simplify. Run the tests after each small change. Never refactor while red.

Then pick the next small behavior and start again at red. A full turn of the loop should take a minute or two, not an hour.

Every example below repeats the small run_suite helper. It starts Minitest with a fixed seed and replaces the timing line with Finished in 0.00s, so the output stays the same on every run. In a real project you would put require "minitest/autorun" at the top of the test file instead.

Step 1: red, a test for code that does not exist

We want a Roman.to_roman(number) method. Start with the easiest possible case: 1 is "I". We write the test first, before there is any Roman at all.

Ruby Red: the test fails because Roman does not exist (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The result is an error (E), NameError: uninitialized constant RomanTest::Roman. That is a perfectly good red: it tells us what to build next. Sometimes the first failure is not an assertion but a missing class or method, and that is fine.

Step 2: green, the simplest thing that works

Now write the least code that satisfies the test. Yes, that really means returning a constant:

Ruby Green: the simplest code that passes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Hard-coding feels like cheating, but it is deliberate: the code does exactly what the test demands and nothing more. The next test will force it to become real. This trick is called triangulation: you add a second example, and the only way to satisfy both is to find the general rule.

Step 3: red again, forcing a general solution

Add tests for 2 and 3. They fail, and the failure message shows exactly what is wrong.

Ruby Red: two more examples break the hard-coded answer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two failures, each with Expected: "II" and Actual: "I" (and the same for three). Now repeating the letter number times is the simplest rule that satisfies all three tests.

Step 4: green, then growing the rules

The tests for 4, 5, 9 and 10 need new knowledge: subtractive notation (IV is 4, IX is 9) and new letters. Rather than writing one test per number by hand, let the test class build tests from a table of examples. This keeps the cases readable and makes adding one a one-line change.

Ruby A table of cases drives the tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

All eleven are green. The implementation is a greedy algorithm: walk the table from the largest value to the smallest, and take each symbol as many times as it fits. Listing 9 => "IX" and 4 => "IV" in the table means the subtractive forms need no special code. If you are not familiar with define_method, define_method and Dynamic Methods explains how the loop creates one test method per case.

Step 5: red for the edge cases

So far we only tested the happy path. TDD also asks: what should happen with 0, a negative number or a text value? Decide the behavior in a test first. We choose: Roman numerals have no zero and no negatives, so those inputs raise an ArgumentError with a helpful message. We also want bigger numbers like 40 (XL) to work, which needs new symbols.

Ruby Red: edge cases that the code does not handle yet (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Three failures again. The zero and negative tests say ArgumentError expected but nothing was raised., because the loop quietly returned an empty string. The test for 40 fails because the table has no XL, so the code builds XXXX. Each red tells us exactly which piece is missing.

Step 6: green for the whole table

Now we make all of them pass: guard clauses at the top for invalid input, and the complete table of Roman symbols including the subtractive pairs (XL, XC, CD, CM). The table lists the pairs in descending order, which is all the greedy algorithm needs.

Ruby Green: guards and the full symbol table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Thirteen runs, all green. The code now handles every number from 1 to 3999, the traditional upper limit (plain Roman numerals have no standard symbol for 5000).

Step 7: refactor under a safety net

The tests are green, so we may improve the design without changing behavior. The while loop works but could be tighter: for each symbol, divmod gives the number of repeats and the remainder in one step. After the edit, the same tests run unchanged. If we made a mistake, a test turns red immediately.

Ruby Refactor: new implementation, same tests, still green

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

SYMBOLS.sum("") adds up strings (the empty string is the starting value), and number.divmod(value) returns the quotient and remainder at once, so no mutable result and no inner loop remain. The test file did not change at all, and that is the point of the safety net: tests describe what the code does, so you can rewrite how freely.

What TDD gives you, and what it costs

Benefits

  • A design that is easy to use. You write the call before the code exists, so awkward interfaces hurt early.
  • Small steps, fewer bugs. When a test goes red, the bug is in the few lines you just wrote.
  • Fearless refactoring. As in step 7, you change structure and let the tests confirm that nothing broke.
  • Living documentation. The tests show how the code is meant to be called.

Costs and limits

  • It is slower at first, and it takes practice to choose small enough steps.
  • Tests for code you do not control (a database, the network, the clock) need test doubles.
  • It does not replace thinking. A wrong requirement tested perfectly is still wrong.
  • Not every task suits it. For exploratory work, such as trying a new library, it is fine to experiment first and add tests once the shape is clear.

Practicing with katas

A kata is a short exercise you repeat to build skill, like scales on a piano. Good ones for Ruby and TDD: FizzBuzz with a twist, converting numbers to words (21 to "twenty-one"), a bowling score calculator, the string calculator (parse "1,2,3" and add), a stack or queue class, a leap-year check, and word wrap. Do each in tiny red-green-refactor steps, and try the same kata again later with a different design.

Common mistakes

  • Writing several tests before any code. Keep exactly one failing test at a time.
  • Skipping the red step. If you never see it fail, you cannot trust it passing.
  • Writing too much code to go green. Make only the current test pass; let the next test demand more.
  • Refactoring on red. Get to green first, then clean up.
  • Testing private methods. Test through the public interface; private details are free to change.
  • Leaving the refactor step out. Without it, TDD produces working but messy code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct order of the TDD cycle?

    You write a failing test (red), write just enough code to pass it (green), and then clean the code up while the tests stay green (refactor).
  2. 2. Why do you run the new test and watch it fail before writing the code?

    A test that has never failed might be asserting nothing. Seeing red first proves the test notices missing behavior.
  3. 3. In the Roman numeral example, why was the first implementation allowed to be a hard-coded "I"?

    TDD asks for the simplest passing code. Adding examples (triangulation) forces the implementation to become general.
  4. 4. When is it safe to restructure the code (refactor)?

    Refactoring changes structure, not behavior. The passing tests prove the behavior is unchanged after each step.
  5. 5. What does assert_raises(ArgumentError) { Roman.to_roman(0) } verify?

    assert_raises passes only if the block raises the given exception class. It also returns the exception so you can check its message.

Summary

  • TDD is a loop: write one failing test (red), make it pass with the simplest code (green), improve the design (refactor).
  • Watching the test fail first proves the test works; errors such as NameError are valid reds.
  • Triangulation uses several examples to force a general solution instead of hard-coded answers.
  • Table-driven tests (a hash of cases plus define_method) keep many examples short and readable.
  • Test the edges (zero, negatives, wrong types) by deciding the behavior in a test first.
  • Refactor only on green and rerun the unchanged tests after every step.
  • TDD helps design and refactoring, but it is a tool, not a rule for every task.

Next: RSpec Overview