Generalizing Solutions with Test Driven Development (Rust)

Introduction to Generalization in TDD

Welcome back to our course on Test-Driven Development (TDD) in Rust. In our previous lesson, we introduced the fundamentals of TDD and the Red-Green-Refactor workflow. Now, we will advance our TDD skills by focusing on generalizing solutions and enhancing the complexity of our testing scenarios using Rust's built-in testing framework.

As a brief reminder, TDD involves a repetitive cycle known as Red-Green-Refactor:

  • Red: Write a failing test to clarify the new functionality you aim to implement.
  • Green: Develop the smallest amount of code needed to make that test pass.
  • Refactor: Clean up the code, enhancing its quality while maintaining its functionality and ensuring all tests remain passing.

In this lesson, we're going to expand upon the sum function, demonstrating how to generalize it while following these TDD principles.

Examining the Current Code Structure

Before we dive into coding, let's review our current setup. You are already familiar with the sum function and its corresponding test script:

pub fn sum(a: i32, b: i32) -> i32 {
    5
}
#[cfg(test)]
mod tests {
    use project::*;

    #[test]
    fn test_sum() {
        let result = sum(2, 3);
        assert_eq!(result, 5);
    }
}

This existing setup serves as a foundation. Now, we'll focus on expanding your understanding by generalizing the approach using TDD principles. Understanding where you've come from will help ensure future changes enhance our function without straying too far from the core logic.

Example: Red Phase - Adding a New Failing Test

To embrace the Red phase, let's introduce a new test case that will fail.

Update the test script to include more input scenarios:

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

    #[test]
    fn test_sum() {
        let result = sum(2, 3);
        assert_eq!(result, 5);
    }

    #[test]
    fn test_sum_again() {
        let result = sum(5, 6);
        assert_eq!(result, 11);
    }
}

By including a new scenario with new inputs, this step is intentionally set to fail to clearly define our target goal.

Running this test will fail and provide output similar to:

Output:

failures:

---- tests::test_sum_again stdout ----
thread 'tests::test_sum_again' panicked at tests/test.rs:14:9:
assertion `left == right` failed
  left: 5
 right: 11
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::test_sum_again

test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out;

This failure confirms that the new functionality needs addressing.

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