Tests are for your future self

May 31, 2024

Key takeaway: Write each test for whoever opens the file next year, and assume that person has none of your context.

Write tests for whoever opens the file next year, because it’s probably you, and you won’t remember why the code works the way it does.

Gergely Orosz wrote about coming back to a side project after months away. He made a change, and the tests he’d written back then caught a regression before it shipped.

Right now you know why the retry count is three and which caller depends on the method returning nil instead of raising. In six months you’ll read that file like someone else wrote it. On a team, the author may have left, and the reasons went with them.

A comment records what you knew the day you wrote it, and it can’t notice when the code drifts. A test runs on every change. Say you fix a bug where “Smith, Jones & Co.” broke the CSV export because the comma wasn’t quoted, and you add a test with a comma in the name. A year later someone swaps in a faster CSV library that quotes differently. By then nobody remembers the bug, but the test still checks for it.

The best time to write that test is now, while you understand the code best. Writing it later means reconstructing the context first, which is the exact work the test was supposed to save. A few habits help:

  • Every bug fix ships with a test that reproduces the bug.
  • Every odd rule, like skipping tax for one region, gets a test so a future change can’t quietly undo it.
  • When you’re about to write a “don’t change this” comment, write a test instead.

“It’s just me” doesn’t last. The prototype becomes the product and the one-off script becomes a scheduled job. A few months away is enough to make you a newcomer to your own code, and that’s when regressions slip through.