Tests that read like sentences
In lesson 111 you tested with Minitest, which comes with Ruby. The other big test tool in the Ruby world is RSpec: you describe how an object behaves, and every example reads like a sentence – expect(stint.in_hours).to eq(1.5). Most Rails apps are tested with it.
RSpec is a gem, or rather several: rspec-core brings describe, it and the runner, rspec-expectations brings expect and the matchers. First the gems and something to test – a Stint, a stretch of work on a project:
install_gem "rspec-core" # describe, it and the runner
install_gem "rspec-expectations" # expect(...).to ...
require "rspec/core"
require "rspec/expectations"
class Stint
attr_reader :project, :minutes, :tags
def initialize(project, minutes)
raise ArgumentError, "not a number" unless minutes.is_a?(Numeric)
@project = project
@minutes = minutes
@tags = []
end
def in_hours
minutes / 60.0
end
def billable?
minutes > 0 && !project.to_s.empty?
end
def tag(name)
tags << name
self
end
end
Stint.new("Website", 90).in_hoursNow the two tests of the Minitest lesson, in RSpec. RSpec.describe Stint do opens an example group for the class; each it "..." do inside is one example, named by a sentence instead of a method name. In the notebook, run_specs runs them:
RSpec.describe Stint do
it "converts minutes to hours" do
expect(Stint.new("Website", 90).in_hours).to eq(1.5)
end
it "is zero hours for zero minutes" do
expect(Stint.new("Website", 0).in_hours).to eq(0.0)
end
end
run_specsOne dot per passing example, then the summary: 2 examples, 0 failures – all green. Side by side with Minitest:
| Minitest | RSpec |
|---|---|
class TestStint < Minitest::Test | RSpec.describe Stint do |
def test_in_hours | it "converts minutes to hours" do |
assert_equal 1.5, x | expect(x).to eq(1.5) |
assert x.valid? | expect(x).to be_valid |
assert_raises(ArgumentError) { ... } | expect { ... }.to raise_error(ArgumentError) |
setup | let, before (per example) |
run_tests | run_specs |
More than eq
eq is a matcher, and RSpec has many: be > 2 compares, include looks into an array or string, raise_error expects an exception. A be_ in front of any name asks the method with a question mark: be_billable calls billable?. not_to turns each of them round.
Groups nest: context "without a project" is a describe that names a situation. And let(:stint) { ... } defines stint for every example below it. The documentation format prints the whole nest:
RSpec.describe Stint do
let(:stint) { Stint.new("Website", 150) }
it "keeps its project" do
expect(stint.project).to eq("Website")
end
it "is longer than two hours" do
expect(stint.in_hours).to be > 2
end
context "with minutes and a project" do
it "is billable" do
expect(stint).to be_billable # calls stint.billable?
end
end
context "without a project" do
let(:stint) { Stint.new("", 150) }
it "is not billable" do
expect(stint).not_to be_billable
end
end
describe "#tag" do
before { stint.tag("meeting") }
it "remembers the tag" do
expect(stint.tags).to include("meeting")
end
end
it "refuses minutes that are not a number" do
expect { Stint.new("Website", "two") }.to raise_error(ArgumentError)
end
end
run_specs "--format", "documentation"Read the indented list from the top and you have the specification of Stint in plain sentences. Three things to notice:
letis built afresh for every example and only when an example uses it. Sotag("meeting")in one example cannot leak into the next. An innerletwith the same name wins: undercontext "without a project",stinthas no project.before { ... }runs before each example of its group – the place for preparation that changes things, likesetupin Minitest.raise_errorneeds a block,expect { ... }, notexpect(...): the code has to run inside RSpec's hands so that RSpec can catch the error. With parentheses, Ruby would raise it beforeexpecteven started.
And when an example fails? Here is a classic slip: an hour and a half, written as 1.3:
RSpec.describe Stint do
it "converts minutes to hours" do
# 1 h 30 min is 1.5 hours, not 1.3
expect(Stint.new("Website", 90).in_hours).to eq(1.3)
end
end
run_specsRSpec shows the line that failed, expected and got, and how it compared (==). The F stands where the dot would be. At the end, rspec chunky.rb:2 is the command that would run just this example again – on your machine, with a real file.
Install the rspec gem – it pulls in rspec-core, rspec-expectations and rspec-mocks (stand-in objects, "doubles"). rspec --init creates the spec/ folder and a .rspec file for your options. The specs go in files ending in _spec.rb:
$ gem install rspec
$ rspec --init# spec/stint_spec.rb
require_relative "../lib/stint"
RSpec.describe Stint do
it "converts minutes to hours" do
expect(Stint.new("Website", 90).in_hours).to eq(1.5)
end
end$ rspec
.
Finished in 0.00211 seconds (files took 0.05 seconds to load)
1 example, 0 failuresThe rspec command runs every *_spec.rb in spec/; rspec spec/stint_spec.rb:4 runs only the example on line 4; --format documentation (also as a line in .rspec) prints the sentences. Which one should you take? Minitest is small and comes with Ruby; RSpec reads like a specification and is what most Rails teams use. Both find the same bugs.
DayLog: a day's hours, added up by project. Write RSpec.describe DayLog with at least two examples, each with an expect – for instance that a new log is empty (be_empty), that total adds up the hours, or that add refuses zero hours (raise_error). Finish with run_specs: the summary must say 0 failures.class DayLog
def initialize
@hours = Hash.new(0)
end
def add(project, hours)
raise ArgumentError, "not positive" unless hours.positive?
@hours[project] += hours
self
end
def total
@hours.values.sum
end
def projects
@hours.keys
end
def empty?
@hours.empty?
end
end
# RSpec.describe DayLog do
# let(:log) { DayLog.new }
#
# it "..." do
# expect(...).to ...
# end
# end
# run_specs