Test-driven development and AI

January 1, 2025

I find test-driven development (TDD) to be a helpful process, especially for fixing bugs and adding small features.

Here is the TDD process:

  • Write a test: The test should fail because the program doesn't have that feature yet or because it replicates an existing bug.
  • Make a code change: Write the simplest code possible to make the test pass.
  • Refactor: Refactor the code to make it more efficient or easier to read.

For bugs, TDD is invaluable. Writing a test that replicates the exact reported issue ensures that the bug is truly fixed when the test passes and stays fixed as long as the test remains part of your suite.

For small features with clear requirements, following TDD and writing tests first helps to ensure that the feature works as expected.

When building large new features, I don't strictly follow TDD. I find I can write code faster without writing tests first, and writing tests first for large features stifles creativity and experimentation. But I do write tests for new features before I consider them done, which helps in refactoring, catching bugs, reducing the risk of regressions, and documenting how the feature works.

AI assistants like ChatGPT and Claude can be valuable tools for writing tests. By providing the code you want to test and requesting test suggestions, you can save time. However, always review AI-generated tests carefully and make adjustments to ensure they are accurate and align with your project's requirements.

For more information on TDD, see Kent Beck's book Test Driven Development: By Example. If you happen to be using my favorite web framework, Django, there is some really good documentation available on writing tests.