Workflow-002: Test-Driven Development with Claude
Document Control
- Workflow ID: 002
- Version: 1.0
- Status: Active
- Complexity: Medium
- Duration: 2-6 hours
- Team Size: 1-3 developers
Overview
Test-Driven Development (TDD) with Claude follows the Red-Green-Refactor cycle, leveraging Claude's ability to write comprehensive tests and implement code that passes them.
┌─────────────────────────────────────────────────────────────────────┐
│ TDD WITH CLAUDE FLOW │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ [1] WRITE TESTS [2] RUN & FAIL [3] IMPLEMENT │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Define specs │ ──► │ Red phase │ ──► │ Green phase │ │
│ │ Write tests │ │ Tests fail │ │ Make tests │ │
│ │ Assert logic │ │ As expected │ │ pass │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │ │
│ └───────────┬───────────┘ │ │
│ ▼ ▼ │
│ [5] COMMIT [4] REFACTOR │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Save progress│◄── │ Clean code │ │
│ │ Tag version │ │ Optimize │ │
│ └──────────────┘ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘Prerequisites
Required SOPs
Environment Setup
- Testing framework configured (pytest, jest, etc.)
- Code coverage tools installed
- CI/CD pipeline ready
Phase 1: Write Tests First
Step 1.1: Define Requirements
bash
# Start with requirements gathering
claude-code "help me understand the requirements for [feature name]"
# Define test cases
claude-code "what test cases should I write for [specific functionality]?"Step 1.2: Generate Test Structure
bash
# Create comprehensive test suite
claude-code "write complete unit tests for a user authentication system with the following requirements:
- Email validation
- Password strength checking
- Login attempt limits
- Session management
- Include edge cases and error scenarios"Example output structure:
python
# test_auth.py
import pytest
from auth import AuthSystem, ValidationError, SecurityError
class TestUserAuthentication:
def test_valid_email_formats(self):
# Test various valid email formats
pass
def test_invalid_email_formats(self):
# Test invalid emails should raise ValidationError
pass
def test_password_strength_requirements(self):
# Test password meets security criteria
pass
def test_login_attempt_limits(self):
# Test account lockout after failed attempts
passStep 1.3: Review and Refine Tests
bash
# Have Claude review the tests
claude-code "review these tests for completeness and best practices"
# Add missing scenarios
claude-code "what edge cases am I missing in these tests?"Phase 2: Red Phase - Run Failing Tests
Step 2.1: Execute Test Suite
bash
# Run tests (they should fail)
claude-code "run the test suite and show me the failures"
# Analyze failure patterns
claude-code "analyze the test failures and create an implementation plan"Step 2.2: Verify Expected Failures
bash
# Confirm tests fail for right reasons
claude-code "verify that tests are failing because functionality isn't implemented, not due to test errors"Quality Gate: All tests fail as expected, no test framework errors
Phase 3: Green Phase - Implement Code
Step 3.1: Minimal Implementation
bash
# Start with simplest implementation
claude-code "implement the minimum code needed to make the first test pass"
# Iterative development
claude-code "now implement the next failing test, one at a time"Step 3.2: Progressive Implementation
bash
# Continue until all tests pass
claude-code "implement the remaining authentication logic to pass all tests"
# Verify each step
claude-code "run tests after each implementation and fix any issues"Step 3.3: Integration Testing
bash
# Test the complete system
claude-code "create integration tests that verify the authentication system works end-to-end"Phase 4: Refactor - Clean and Optimize
Step 4.1: Code Quality Review
bash
# Analyze code quality
claude-code "review the implementation for code quality, performance, and maintainability"
# Suggest improvements
claude-code "refactor this code to be more readable and efficient while keeping all tests passing"Step 4.2: Performance Optimization
bash
# Optimize performance
claude-code "identify performance bottlenecks and optimize without breaking tests"
# Add performance tests
claude-code "add performance tests to ensure the system meets response time requirements"Phase 5: Commit and Document
Step 5.1: Final Validation
bash
# Run complete test suite
claude-code "run all tests including unit, integration, and performance tests"
# Check code coverage
claude-code "generate code coverage report and identify any gaps"Step 5.2: Documentation
bash
# Generate documentation
claude-code "create comprehensive documentation for the authentication system including API docs and usage examples"
# Commit with proper message
claude-code "create a detailed commit message for this TDD implementation"Advanced TDD Patterns
Parameterized Testing
bash
claude-code "convert these similar tests into parameterized tests to reduce duplication"Mock and Stub Generation
bash
claude-code "create mocks for external dependencies in the authentication system"Property-Based Testing
bash
claude-code "add property-based tests using hypothesis to test authentication edge cases"Common Anti-Patterns to Avoid
1. Writing Too Much Code
bash
# Wrong approach
claude-code "implement the complete authentication system"
# Correct approach
claude-code "implement just enough to make this one test pass"2. Testing Implementation Details
bash
# Focus on behavior, not implementation
claude-code "write tests that verify behavior, not internal implementation details"3. Skipping Refactor Phase
bash
# Always refactor after green
claude-code "now that tests pass, refactor for better design while maintaining test coverage"Success Metrics
| Metric | Target | Measurement |
|---|---|---|
| Test Coverage | >90% | Line coverage |
| Test-to-Code Ratio | 1:1 to 2:1 | Lines of test code vs production code |
| Defect Rate | <1% | Post-deployment bugs |
| Build Time | <5 min | Full test suite execution |
Troubleshooting
Issue: Tests are flaky
bash
# Solution: Identify and fix non-deterministic behavior
claude-code "analyze these flaky tests and make them deterministic"Issue: Tests take too long
bash
# Solution: Optimize test performance
claude-code "optimize these slow tests by using mocks and reducing I/O"Issue: Hard to test code
bash
# Solution: Refactor for testability
claude-code "refactor this tightly-coupled code to be more testable"Integration with CI/CD
GitHub Actions Example
yaml
# .github/workflows/tdd.yml
name: TDD Workflow
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run TDD Tests
run: |
npm test
npm run coverage
- name: Comment Coverage
uses: actions/comment-coverage@v1Best Practices
- Start with Failing Test: Always write test first
- One Test at a Time: Don't write multiple tests before implementing
- Minimal Implementation: Write just enough code to pass
- Refactor Regularly: Clean code after each green phase
- Fast Feedback: Keep tests fast and reliable
See Also
- Workflow-001: Explore-Plan-Code
- SOP-013: Testing Framework Setup
- SOP-012: Error Handling Setup
- Quick Ref: Testing Commands
Next Workflow: Try Visual Development for UI-focused projects