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:
gem install colorize --no-document 2>&1 | tail -1
ruby -e 'require "colorize"; puts "installed and loaded: #{"ok".red.uncolorize}"'
gem list colorizeinstalled 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:
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"
endcd 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)$"--- Gemfile.lock (first lines):
GEM
remote: https://rubygems.org/
specs:
bigdecimal (4.1.3)
minitest
money
rakebundle installresolves compatible versions of every gem and their dependencies, installs them, and records the exact versions inGemfile.lock. Commit both files.- On another machine,
bundle installinstalls exactly the locked versions. bundle exec rake testruns a command with the project's gems.bundle update moneyupgrades one gem within its allowed range;bundle outdatedlists newer versions.
⚠️ Since Ruby 3.4, some libraries left the standard library and became gems:
bigdecimal,csv,base64,mutex_mand others. If a gem you use needs one of them, list it in your Gemfile, as withbigdecimalabove. 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.
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
endTesting with Minitest
Minitest comes with Ruby. A test class has methods starting with test_, and each uses assertions:
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
endcd 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/'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:
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.rb1) 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:
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: :testcd shop
bundle exec rake -T
bundle exec rake receipt
bundle exec rake 2>&1 | grep -E "runs, "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:
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
endRun 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
- Create a project with a Gemfile that uses the
fakergem, install it, and print three fake names. - Add a
remove(sku)method toCartand write two tests for it. - Add a Rake task
rake statsthat prints how many lines are inlib/. - Rewrite one Minitest test in RSpec style.
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?