env.dev

Test-Driven Development with AI

Combine TDD methodology with LLM assistants. Write tests first, then use AI to implement passing code.

Overview

Test-Driven Development (TDD) with LLMs combines the red-green-refactor cycle with AI code generation. You write the test (specification), the LLM writes the implementation. This produces more reliable AI-generated code because the test serves as an unambiguous contract.

The TDD + AI Workflow

  • RED: Write a failing test that describes the desired behavior
  • GREEN: Provide the test to the LLM and ask it to write passing code
  • RUN: Execute the test to verify it passes
  • ITERATE: If it fails, share the error with the LLM to fix
  • REFACTOR: Once green, ask the LLM to improve the code while keeping tests green
  • REPEAT: Add the next test case and repeat

Example Prompt

Prompt
Here is a failing test. Write the implementation that makes it pass.

```typescript
import { describe, it, expect } from 'vitest';
import { parseSearchQuery } from './search.ts';

describe('parseSearchQuery', () => {
  it('parses simple terms', () => {
    expect(parseSearchQuery('hello world')).toEqual({
      terms: ['hello', 'world'],
      filters: {},
    });
  });

  it('extracts key:value filters', () => {
    expect(parseSearchQuery('type:bug urgent')).toEqual({
      terms: ['urgent'],
      filters: { type: 'bug' },
    });
  });
});
```

Write only the parseSearchQuery function. Export it as a named export.

Tips

Start with the simplest test case, add complexity incrementally, always run tests between iterations, and let the LLM suggest edge case tests you may have missed. TDD with AI is one of the most reliable ways to get correct generated code.

Frequently Asked Questions

How does TDD work with LLMs?

Write the test first (red), then ask the LLM to write the implementation that makes it pass (green), then refactor together. The test serves as an unambiguous specification for the AI.

Why is TDD especially effective with AI?

Tests give the LLM a concrete, verifiable specification. Instead of interpreting vague requirements, the AI has an objective target. This dramatically reduces hallucination.