Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
55: Writing Tests with Minitest
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
ShoppingCartclass to include thetotal_with_taxmethod. - Create a corresponding test method in
ShoppingCartTestthat 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_deltainstead ofassert_equalif you run into rounding issues, but for simple integers,assert_equalshould suffice).
There are no comments for now.