文のように読めるテスト
レッスン111では、Rubyに最初から付いてくるMinitestでテストしました。Rubyの世界にはもう1つ大きなテスト道具があります。RSpecです。オブジェクトがどうふるまうかを記述(describe)し、1つひとつの例が文のように読めます。expect(stint.in_hours).to eq(1.5)のようにです。Railsアプリの多くはRSpecでテストされています。
RSpecはgemです。正確にはいくつかのgemの集まりです。rspec-coreはdescribe、itとテストを実行する仕組みを、rspec-expectationsはexpectとマッチャーを持ってきます。まずはgemと、テストする対象を用意しましょう。Stintは、あるプロジェクトでのひと区切りの作業です。
install_gem "rspec-core" # describe、it、テストを実行する仕組み
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_hoursでは、Minitestのレッスンの2つのテストをRSpecで書いてみます。RSpec.describe Stint doは、このクラスのexample group(例のグループ)を開きます。中のit "..." doの1つひとつがexample(例)で、メソッド名の代わりに文で名前を付けます。このノートブックではrun_specsで実行します。
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_specs成功した例1つにつき点が1つ、そのあとにまとめが出ます。2 examples, 0 failures、オールグリーンです。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 (例ごとに) |
run_tests | run_specs |
eqだけではありません
eqはマッチャーの1つで、RSpecにはたくさんのマッチャーがあります。be > 2は大小を比べ、includeは配列や文字列の中を調べ、raise_errorは例外が起きることを期待します。どんな名前でも前にbe_を付けると、疑問符付きのメソッドを呼び出します。be_billableはbillable?を呼びます。not_toを使えば、どれも逆の意味になります。
グループは入れ子にできます。context "without a project"は、ある状況に名前を付けるdescribeです。そしてlet(:stint) { ... }は、その下のすべての例で使えるstintを定義します。documentation形式で出力すると、入れ子全体が見えます。
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 # 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"字下げされた一覧を上から読むと、Stintの仕様がそのまま文になっています。注目してほしい点が3つあります。
letは例ごとに新しく作られ、しかもその例が使ったときに初めて作られます。ですから、ある例でのtag("meeting")が次の例に漏れることはありません。内側で同じ名前のletを書くと、そちらが優先されます。context "without a project"の中では、stintにプロジェクトがありません。before { ... }は、そのグループの各例の前に実行されます。Minitestのsetupのように、何かを変更する準備はここに書きます。raise_errorにはexpect(...)ではなく、ブロック付きのexpect { ... }が必要です。RSpecがエラーを受け止められるように、コードはRSpecの手の中で実行されなければなりません。丸かっこだと、expectが動き出す前にRubyが例外を投げてしまいます。
では、例が失敗したらどうなるでしょう?よくある書き間違いです。1時間半を1.3と書いてしまいました。
RSpec.describe Stint do
it "converts minutes to hours" do
# 1時間30分は1.5時間で、1.3時間ではありません
expect(Stint.new("Website", 90).in_hours).to eq(1.3)
end
end
run_specsRSpecは失敗した行と、expected(期待した値)とgot(実際の値)、そして比べ方(==)を表示します。点の代わりにFが出ています。最後のrspec chunky.rb:2は、この例だけをもう一度実行するコマンドです。自分のコンピューターで、本物のファイルがあれば使えます。
rspec gemをインストールします。rspec-core、rspec-expectations、それにrspec-mocks(オブジェクトの代役「ダブル」)がいっしょに入ります。rspec --initはspec/フォルダーと、オプションを書いておく.rspecファイルを作ります。スペックは名前が_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 failuresrspecコマンドはspec/の中のすべての*_spec.rbを実行します。rspec spec/stint_spec.rb:4なら4行目の例だけを、--format documentation(.rspecに1行書いてもOK)なら文の形で表示します。どちらを使えばいいでしょう?Minitestは小さく、Rubyに付いてきます。RSpecは仕様書のように読め、Railsのチームの多くが使っています。どちらでも同じバグを見つけられます。
DayLogです。1日の作業時間をプロジェクトごとに合計します。RSpec.describe DayLogを書き、expectを使った例を2つ以上作りましょう。たとえば、新しいログが空であること(be_empty)、totalが時間を合計すること、addが0時間を受け付けないこと(raise_error)などです。最後にrun_specsを実行して、まとめに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