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
30: Writing Tests with RSpec
I've spent a lot of my career fixing bugs that "looked" fine in the editor but exploded the moment they hit production. Usually, it's because the developer tested the "happy path"—the scenario where everything goes right—and completely ignored the edge cases. This is exactly why we use RSpec.
Take a look at this simple BankAccount class. At a glance, it looks perfectly reasonable. It has a balance, you can deposit, and you can withdraw.
class BankAccount attr_reader :balance def initialize(starting_balance) @balance = starting_balance end def deposit(amount) @balance += amount end def withdraw(amount) @balance -= amount end endThe Silent Balance Drain
If you're just running this in a REPL, you might try
account.withdraw(50)and see it work. But there's a massive logic hole here: I can withdraw a million dollars from an account that only has ten. Ruby will happily let the balance go negative, which is a disaster for a bank.Instead of just adding an
ifstatement and hoping for the best, let's write a test to prove this failure. This is the "Red" part of the Red-Green-Refactor cycle. I'll create a spec file that describes exactly how I expect the withdrawal to behave when funds are low.# bank_account_spec.rb require_relative 'bank_account' RSpec.describe BankAccount do it 'does not allow withdrawing more than the current balance' do account = BankAccount.new(100) # We expect this to raise an error, not just let the balance drop expect { account.withdraw(150) }.to raise_error(RuntimeError, "Insufficient funds") end endWhen you run this with
rspec bank_account_spec.rb, it fails miserably. RSpec tells us that it expected aRuntimeError, but instead, the code just executed and left the balance at -50. The test has successfully exposed the bug.Adding Guard Clauses and Expectations
Now we fix it. I'm going to add a guard clause to the
withdrawmethod. A guard clause is a pattern where we handle the "error" condition early and exit the method immediately, keeping the rest of the logic clean.class BankAccount attr_reader :balance def initialize(starting_balance) @balance = starting_balance end def deposit(amount) @balance += amount end def withdraw(amount) raise "Insufficient funds" if amount > @balance @balance -= amount end endRun the test again. It passes. But we aren't done. A professional test suite doesn't just test the failures; it ensures the successful paths still work. I'll add a few more specs to cover the basics.
RSpec.describe BankAccount do let(:account) { BankAccount.new(100) } it 'increases balance after a deposit' do account.deposit(50) expect(account.balance).to eq(150) end it 'decreases balance after a valid withdrawal' do account.withdraw(40) expect(account.balance).to eq(60) end it 'raises an error for insufficient funds' do expect { account.withdraw(150) }.to raise_error(RuntimeError, "Insufficient funds") end endNotice I used
let(:account) { ... }here. In RSpec,letis a way to define a memoized helper method. It's cleaner than defining the account inside every singleitblock, and it ensures each test starts with a fresh account object so they don't interfere with one another.Choosing the Right Matcher
One thing that trips people up is choosing the right "matcher"—the part after
expect(...).to. Whileeqis the workhorse for checking equality, you'll often need others. If you're checking if a list contains an item, useinclude. If you're checking if a value is true or false, usebe trueorbe_truthy. If you're testing that a block of code crashes (like our withdrawal error), you must wrap the call in curly braces{ }rather than parentheses( ), otherwise Ruby will execute the code before RSpec can "catch" the error.
📋 Practical Task
Building a Tax Calculator with RSpec
Your task is to create a TaxCalculator class and a corresponding RSpec test suite to ensure it handles various tax brackets and edge cases correctly.
Requirements:
- Create a
TaxCalculatorclass with a methodcalculate_tax(amount). - The logic should be:
- Amounts $0 or less should raise a
ArgumentErrorwith the message "Amount must be positive". - Amounts up to $1,000 are taxed at 10%.
- Amounts over $1,000 are taxed at 20%.
- Amounts $0 or less should raise a
- Write an RSpec file that includes:
- A
letblock to initialize the calculator. - A test case for the 10% bracket (e.g., $500 should result in $50).
- A test case for the 20% bracket (e.g., $2,000 should result in $400).
- A test case verifying that negative numbers raise the
ArgumentError.
- A
Goal: Run your specs and ensure all tests pass. Focus on using the correct matchers (eq for the calculations and raise_error for the validation).
There are no comments for now.