Introduction and Overview

By now, you should be familiar with the basics of Test-Driven Development (TDD) and its iterative Red-Green-Refactor cycle. This lesson focuses on honing your TDD mindset, a perspective that prioritizes writing tests before coding, which can dramatically improve code clarity, reliability, and maintainability.

We'll continue using Ruby and RSpec, tools that streamline our test-driven approach in Ruby projects. RSpec is celebrated for its readability and the expressive nature of its syntax, making it an excellent choice for implementing TDD principles in our projects.

Let's explore this mindset further with practical examples and visualize the flow of thinking in tests.

Example: `calculate_total` Method (Red Phase)

Let's begin by writing tests for a method 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 method that calculates lists of items. 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.

Explanation:

  • We know we want a method called calculate_total(), so we'll write a test that uses it.
  • For now, we know that we want an empty array as input to return 0, so we can write that test.
  • The expectation is that these tests will initially fail, which is an integral part of the Red phase.
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