Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

RB
Ruby
0/12 completed
Beginner
Hello RubyVariables and typesConditions and loopsMethods
Intermediate
Arrays and hashesBlocks, procs and iteratorsClasses and objectsModules and mixins
Advanced
Exceptions and filesMetaprogramming
Pro
Gems, Bundler and testingRuby on Rails basics
Tracks / Ruby / Pro

Gems, Bundler and testing

Real Ruby projects use gems (packages) written by others, manage them with Bundler, run tasks with Rake, and check their code with automated tests. This lesson sets up a small project the way professional Ruby developers do.

💡 Gems are installed from the internet, which the in-browser editors can't do. The examples in this lesson are terminal commands; every output shown was produced by running them with Ruby 4.0 on Linux.

Gems

A gem is a packaged Ruby library. The public registry, rubygems.org, has over 180,000 of them. gem installs them:

bash
gem install colorize --no-document 2>&1 | tail -1
ruby -e 'require "colorize"; puts "installed and loaded: #{"ok".red.uncolorize}"'
gem list colorize
Output
installed and loaded: ok

*** LOCAL GEMS ***

colorize (1.1.0)

gem install puts the gem on your whole machine. That's fine for tools, but for projects you want each project to declare its own gems and versions, so everyone on the team (and the server) uses the same ones. That's Bundler's job.

Bundler and the Gemfile

A Gemfile lists a project's gems:

shop/Gemfile
source "https://rubygems.org"

gem "money", "~> 6.19"
gem "bigdecimal"   # money needs it; it left the standard library in Ruby 3.4

group :development, :test do
  gem "minitest", "~> 5.25"
  gem "rake"
end
bash
cd shop
bundle install --quiet 2>&1 | grep -v "^$" | head -3
echo "--- Gemfile.lock (first lines):"
sed -n '1,4p' Gemfile.lock
bundle list --name-only | grep -E "^(money|minitest|rake)$"
Output
--- Gemfile.lock (first lines):
GEM
  remote: https://rubygems.org/
  specs:
    bigdecimal (4.1.3)
minitest
money
rake
  • bundle install resolves compatible versions of every gem and their dependencies, installs them, and records the exact versions in Gemfile.lock. Commit both files.
  • On another machine, bundle install installs exactly the locked versions.
  • bundle exec rake test runs a command with the project's gems.
  • bundle update money upgrades one gem within its allowed range; bundle outdated lists newer versions.

⚠️ Since Ruby 3.4, some libraries left the standard library and became gems: bigdecimal, csv, base64, mutex_m and others. If a gem you use needs one of them, list it in your Gemfile, as with bigdecimal above. Without it, require "money" fails with cannot load such file -- bigdecimal.

Version constraints:

Constraint Means
"~> 6.19" ≥ 6.19 and < 7.0 (the "pessimistic" operator, the usual choice)
"~> 6.19.1" ≥ 6.19.1 and < 6.20
">= 2.0" 2.0 or newer, any major version
(none) Any version

A small project

The usual layout: code in lib/, tests in test/ (or spec/ with RSpec), and a Rakefile for tasks.

shop/lib/cart.rb
require "money"

Money.rounding_mode = BigDecimal::ROUND_HALF_UP
Money.locale_backend = nil

class Cart
  Item = Data.define(:sku, :price, :qty)

  attr_reader :items

  def initialize(currency: "INR")
    @currency = currency
    @items = []
  end

  def add(sku, price_cents, qty: 1)
    raise ArgumentError, "quantity must be positive" unless qty.positive?
    @items << Item.new(sku:, price: Money.new(price_cents, @currency), qty:)
    self
  end

  def total = items.sum(Money.new(0, @currency)) { it.price * it.qty }

  def apply_discount(percent)
    raise ArgumentError, "discount must be 0-100" unless (0..100).cover?(percent)
    total * (100 - percent) / 100
  end
end

Testing with Minitest

Minitest comes with Ruby. A test class has methods starting with test_, and each uses assertions:

shop/test/cart_test.rb
require "minitest/autorun"
require_relative "../lib/cart"

class CartTest < Minitest::Test
  def setup
    @cart = Cart.new
  end

  def test_empty_cart_totals_zero
    assert_equal Money.new(0, "INR"), @cart.total
  end

  def test_total_adds_price_times_quantity
    @cart.add("KB-1", 4950).add("MS-2", 1999, qty: 2)
    assert_equal 8948, @cart.total.cents
  end

  def test_discount
    @cart.add("KB-1", 10_000)
    assert_equal 9_000, @cart.apply_discount(10).cents
  end

  def test_rejects_bad_quantity
    error = assert_raises(ArgumentError) { @cart.add("X", 100, qty: 0) }
    assert_match(/positive/, error.message)
  end
end
bash
cd shop
bundle exec ruby test/cart_test.rb --seed 1 | sed -E 's/in [0-9.]+s/in 0.00Xs/; s/[0-9.]+ runs\/s/N runs\/s/; s/[0-9.]+ assertions\/s/N assertions\/s/'
Output
Run options: --seed 1

# Running:

....

Finished in 0.00Xs, N runs/s, N assertions/s.

4 runs, 6 assertions, 0 failures, 0 errors, 0 skips

Each . is a passing test. setup runs before every test, so each starts with a fresh cart. Now let's break the code on purpose and see a failure:

bash
cd shop
sed -i 's/(100 - percent) \/ 100/(100 + percent) \/ 100/' lib/cart.rb
bundle exec ruby test/cart_test.rb --seed 1 2>&1 | sed -n '/Failure/,/^$/p' | sed -E 's/\[[^]]*cart_test.rb/[test\/cart_test.rb/'
sed -i 's/(100 + percent) \/ 100/(100 - percent) \/ 100/' lib/cart.rb
Output
  1) Failure:
CartTest#test_discount [test/cart_test.rb:20]:
Expected: 9000
  Actual: 11000

The failure names the test, the line, and the expected and actual values.

Assertion Checks
assert x / refute x Truthy / falsy
assert_equal expected, actual Equality (expected value first)
assert_nil x, assert_empty x, assert_includes list, x Common shapes
assert_in_delta 0.3, 0.1 + 0.2, 0.001 Floats, with a tolerance
assert_raises(Error) { … } That the block raises
assert_match /re/, text A regular expression matches

Rake tasks

A Rakefile defines project tasks, written in Ruby:

shop/Rakefile
require "rake/testtask"

Rake::TestTask.new(:test) do |t|
  t.libs << "lib"
  t.test_files = FileList["test/**/*_test.rb"]
end

desc "Print a demo receipt"
task :receipt do
  require_relative "lib/cart"
  cart = Cart.new.add("KB-1", 4950).add("MS-2", 1999, qty: 2)
  cart.items.each { |i| puts format("%-6s x%d  %s", i.sku, i.qty, (i.price * i.qty).format) }
  puts "Total: #{cart.total.format}"
end

task default: :test
bash
cd shop
bundle exec rake -T
bundle exec rake receipt
bundle exec rake 2>&1 | grep -E "runs, "
Output
rake receipt  # Print a demo receipt
rake test     # Run tests
KB-1   x1  ₹49.50
MS-2   x2  ₹39.98
Total: ₹89.48
4 runs, 6 assertions, 0 failures, 0 errors, 0 skips

rake -T lists the described tasks, and rake alone runs the default (the tests).

RSpec, briefly

Many teams use RSpec instead of Minitest. It reads like a specification:

ruby
RSpec.describe Cart do
  subject(:cart) { Cart.new }

  it "totals price times quantity" do
    cart.add("KB-1", 4950).add("MS-2", 1999, qty: 2)
    expect(cart.total.cents).to eq(8948)
  end

  it "rejects a zero quantity" do
    expect { cart.add("X", 100, qty: 0) }.to raise_error(ArgumentError, /positive/)
  end
end

Run it with bundle exec rspec. Both frameworks are excellent; Rails uses Minitest by default, and RSpec is very popular in Rails companies.

Code quality tools

Tool Does
RuboCop Checks style and common mistakes; rubocop -a fixes many automatically
Standard RuboCop with a fixed, no-arguments configuration
SimpleCov Measures test coverage
bundler-audit Checks your Gemfile.lock for gems with known vulnerabilities

Practice

  1. Create a project with a Gemfile that uses the faker gem, install it, and print three fake names.
  2. Add a remove(sku) method to Cart and write two tests for it.
  3. Add a Rake task rake stats that prints how many lines are in lib/.
  4. Rewrite one Minitest test in RSpec style.
✎ Check your understanding

1.What is Gemfile.lock for?

2.What does gem "money", "~> 6.19" allow?

3.In Minitest, which method runs before every test?

4.In assert_equal a, b, which is the expected value?

← Metaprogramming