Test-Driven Development (TDD) follows this development cycle:
- Red: Write a failing test first.
- Green: Implement the minimum necessary code to pass the test.
- Refactor: Improve the code while ensuring tests still pass.
- Tests define the specification: Test code expresses the expected behavior of the implementation.
- Follow the Arrange-Act-Assert pattern:
- Arrange: Set up the necessary test environment.
- Act: Execute the functionality under test.
- Assert: Verify the expected result.
- Test names should follow a "Condition → Action → Expected Result" format. Example:
"Given a valid token, retrieving user information should succeed"
Once tests pass, use the following tools to refine your code:
- Run
cargo check
for type checking and borrow checking. - Use
cargo clippy
to detect potential issues and enforce best practices.
- Run
cargo deadlinks
to check for dead documentation links. - Use
cargo udeps
to find unused dependencies. - Run
cargo rustc -- -W dead_code
to detect unused functions.
- Install
cargo-tarpaulin
for test coverage measurement:cargo install cargo-tarpaulin cargo tarpaulin --out html
- Open the generated HTML report to review coverage.
- Commit after each phase (test creation → implementation → refactoring).
- Review changes before committing:
git status # Check modified files git add <relevant files> git commit -m "<appropriate commit message>"
- Use commit prefixes for clarity:
test:
- Adding or modifying testsfeat:
- Implementing new featuresrefactor:
- Code refactoring
For more details on TDD practices in Rust, naming conventions for tests, and best practices for refactoring, refer to:
.docs/tdd-rust-guidelines.md
This file includes step-by-step instructions for test-first development, structuring test cases, and leveraging Rust’s testing framework efficiently.