クイックリファレンス

RSpec チートシート

RSpecの総合リファレンスガイド:RubyにおけるBDDテスト、describe、context、it、マッチャー、let、subject、モック、スパイ。

· 公開日

RSpec は、Ruby向けの振る舞い駆動開発(BDD)テストフレームワークです。

基本のSpec構造

RSpec.describe Calculator do
  let(:calculator) { Calculator.new }

  describe "#add" do
    context "when adding positive numbers" do
      it "returns the arithmetic sum" do
        expect(calculator.add(2, 3)).to eq(5)
      end
    end

    context "when given invalid input" do
      it "raises an ArgumentError" do
        expect { calculator.add(2, "x") }.to raise_error(ArgumentError)
      end
    end
  end
end

主要マッチャー

# 等価性
expect(actual).to eq(expected)       # 値の等価性 (==)
expect(actual).to be(expected)       # オブジェクトの同一性 (equal?)

# 真偽値と述語メソッド
expect(actual).to be_truthy
expect(actual).to be_nil
expect(user).to be_active            # user.active? を呼び出す

# コレクション
expect(list).to include("ruby")
expect(list).to match_array([1, 2])  # 順序を問わず同一の要素を含む
expect(list).to be_empty

# 比較
expect(value).to be > 10
expect(value).to be_between(1, 100).inclusive

# エラーと例外
expect { risky_call }.to raise_error(StandardError, /message/)
expect { safe_call }.not_to raise_error

モックとスタブ (rspec-mocks)

# メソッドのスタブ化
allow(user).to receive(:name).and_return("Alice")

# メソッド呼び出しの検証
expect(notifier).to receive(:send_email).with("[email protected]").once

# ダブル(モックオブジェクト)
mock_service = double("PaymentService", charge: true)

参考資料

関連テーマ