The TDD Mindset: Thinking in Tests with Rust

Introduction and Overview

In this lesson, we'll deepen our understanding of the Test-Driven Development (TDD) mindset by focusing on the Red-Green-Refactor cycle with a practical example centered on a calculate_total function. This example will guide you through the process of thinking in tests, prioritizing test writing, and leveraging TDD to enhance code clarity, reliability, and maintainability.

Using Rust and its built-in testing framework, we will follow these steps:

  • Begin with the Red phase by identifying and writing failing tests for the calculate_total function, which will compute the total price of items in a shopping cart.
  • Move to the Green phase to implement the minimal code required to pass each test, ensuring that the calculate_total function behaves as expected.
  • Enter the Refactor phase to improve the code structure and readability of calculate_total, employing idiomatic Rust solutions while keeping tests green.
  • Utilize Rust's built-in testing tools to efficiently integrate the TDD approach within our Rust project.

By working through this example, you'll gain practical experience with TDD principles and develop the calculate_total function in a way that showcases how TDD fosters code quality and robustness.

Example: calculate_total Function (Red Phase)

Let's begin by writing tests for a function named calculate_total, designed to compute the total price of items in a shopping cart. This is where you engage with the Red phase: write a failing test.

Let's think about how to build a function that calculates the total price of items in a shopping cart. What should the interface be? How does the consumer of the code use it? These are the questions we think about first when we "think in tests." Here's one way we might think about it in Rust.

Rust
#[cfg(test)]
mod tests {
    use project::*;

    #[test]
    fn calculate_total_returns_zero_for_empty_vector() {
        let result = calculate_total(vec![]);
        assert_eq!(result, 0.0);
    }
}

Explanation:

  • We know we want a function called calculate_total(), so we'll write a test that uses it.
  • For now, we know that we want an empty vector as input to return 0, so we can write that test.
  • At this point, the code won't even compile because calculate_total doesn't exist yet. This compilation failure is part of the Red phase in TDD.

Running this will result in compilation errors, confirming we're in the Red phase and creating a clear path for subsequent development.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal