Skip to Content
Course content

55: Writing Tests with Minitest

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely written plenty of code by now that you "know" works because you ran it once and it didn't crash. But as your projects grow, that manual checking becomes a nightmare. That's where Minitest comes in. I like Minitest because it's bundled with Ruby—no heavy gems to install—and it doesn't try to hide the Ruby language behind a complex domain-specific language. It's just Ruby.

To show you how this works, let's build a ShoppingCart class. It's a simple enough concept, but it has enough moving parts to make testing actually feel useful.

Setting the Stage for our Shopping Cart

First, I'll sketch out a basic class. I want to be able to add items (which are just hashes with a name and price) and get a total. I'm going to keep this in a file called shopping_cart.rb.

class ShoppingCart
  attr_reader :items

  def initialize
    @items = []
  end

  def add_item(item)
    @items << item
  end

  def total
    @items.sum { |item| item[:price] }
  end
end

Now, instead of running this script and using puts to see if it works, I'm going to create a separate test file: shopping_cart_test.rb. In Minitest, we create a class that inherits from Minitest::Test. Any method that starts with test_ will be run automatically.

require 'minitest/autorun'
require_relative 'shopping_cart'

class ShoppingCartTest < Minitest::Test
  def test_adding_an_item_increases_count
    cart = ShoppingCart.new
    cart.add_item({ name: "Mechanical Keyboard", price: 100 })
    
    assert_equal 1, cart.items.count
  end

  def test_total_calculates_correctly
    cart = ShoppingCart.new
    cart.add_item({ name: "Mouse", price: 50 })
    cart.add_item({ name: "Pad", price: 20 })
    
    assert_equal 70, cart.total
  end
end

Tripping over a Discount Logic Bug

Now I want to add a feature: a discount code. This is where testing actually saves your skin. I'll write the test first—a habit I've picked up over the years—to define what "success" looks like.

def test_apply_discount_reduces_total
  cart = ShoppingCart.new
  cart.add_item({ name: "Headphones", price: 100 })
  
  # I want a 10% discount to bring 100 down to 90
  assert_equal 90, cart.apply_discount(10)
end

If I run this now, it fails because apply_discount doesn't exist. So, I'll implement it in shopping_cart.rb. Here is where I'm going to make a classic mistake. I'll write the logic quickly without thinking about the math types.

def apply_discount(percentage)
  total - percentage
end

I just realized what I did. I subtracted the number 10 from the total instead of calculating 10% of the total. When I run the test, Minitest screams at me: Expected: 90, Actual: 90... wait, in this specific case (100 - 10), it actually passed! But if my total was 200, 200 - 10 is 190, while a 10% discount should be 180. My test was too simple to catch my bug.

I'll add a second test case with a different total to expose the flaw:

def test_apply_discount_with_different_total
  cart = ShoppingCart.new
  cart.add_item({ name: "Monitor", price: 200 })
  assert_equal 180, cart.apply_discount(10)
end

Now it fails spectacularly. I'll fix the logic to actually handle percentages:

def apply_discount(percentage)
  total * (1 - percentage / 100.0)
end

Cleaning up the Repetition

Looking at my test file, I'm noticing that every single test starts with cart = ShoppingCart.new. It's tedious and cluttered. Minitest gives us a setup method that runs before every single test case. I can move the initialization there to keep my tests lean.

class ShoppingCartTest < Minitest::Test
  def setup
    @cart = ShoppingCart.new
  end

  def test_adding_an_item_increases_count
    @cart.add_item({ name: "Mechanical Keyboard", price: 100 })
    assert_equal 1, @cart.items.count
  end

  def test_total_calculates_correctly
    @cart.add_item({ name: "Mouse", price: 50 })
    @cart.add_item({ name: "Pad", price: 20 })
    assert_equal 70, @cart.total
  end
end

Now each test focuses only on the action and the assertion. It's much easier to read at a glance.




📋 Practical Task

Implementing a Sales Tax Calculator for the Shopping Cart

Your task is to extend the ShoppingCart example. You need to implement a method called total_with_tax(tax_rate) that takes a percentage (e.g., 8 for 8%) and returns the total price including that tax.

To complete this exercise:

  • Modify the ShoppingCart class to include the total_with_tax method.
  • Create a corresponding test method in ShoppingCartTest that verifies the tax is calculated correctly. For example, a total of 100 with a tax rate of 7 should return 107.0.
  • Ensure your test handles floating point numbers correctly (Hint: you might want to use assert_in_delta instead of assert_equal if you run into rounding issues, but for simple integers, assert_equal should suffice).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.