結論

RSpec は describe でまとめ、it に1つの振る舞い、expect で結果を確かめて書きます。

この記事でわかること

  • マッチャ・モックの早見表
  • minitest で動かした対応表と出力
  • Rails・FactoryBot・Serverspec

2026年12月1日更新|公式とRuby 3.3で確認

書きたいことごとの書き方です。1列目から詳しい節へ移れます。

書きたいことRSpec の書き方
値が等しいexpect(x).to eq 12
条件で分けるcontext "〜のとき" do
準備を共通化let(:card) {
PointCard.new }
含む・例外・変化include・raise_error
change
戻り値の差し替えallow(obj)
.to receive(:m)
.and_return(1)
呼ばれたか確認expect(obj)
.to receive(:m)
テストの使い回しit_behaves_like
"名前"
失敗だけ再実行rspec
--only-failures

確認環境:RSpec の版・書き方・出力の文言は、rspec.info の RSpec 3.13 のドキュメント、rubygems.org、GitHub の rspec・rspec-rails の Changelog と README で確かめました。rspec-rails・factory_bot・Serverspec も、それぞれの公式のドキュメントとソースで確かめました。RSpec の実行画面の動作はこの環境では確かめていない。手元では Ubuntu 24.04.5 LTS・Ruby 3.3.6 と同梱の minitest 5.20.0 で、RSpec と同じ形のテストを minitest で書いて動かし、出力をそのまま載せました(確認日 2026年12月1日)。

本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。

(記載例)出典:株式会社RJC「RSpecの書き方入門|マッチャ・モック早見表とminitest対応表」

RSpecとは|Rubyのテストを「仕様」の文で書く道具

この節では、RSpec が何をする道具で、今どの版が出ているかが分かります。

RSpec は、Ruby のコードが期待どおりに動くかを確かめるテストの道具(gem)です。 公式サイトは「Behaviour Driven Development for Ruby.」と紹介しています。「PointCard の #points は、ゴールド会員のとき2倍になる」のように、振る舞いを文で並べる形で書くのが特徴です。中身は rspec-core(枠組み)・rspec-expectations(確かめ)・rspec-mocks(置き換え)の3つの gem で、rspec を入れるとまとめて入ります。

3.13系今の安定版rspec-core 3.13.7
4.0beta1次の版の試験版2026年2月18日
8.1.0rspec-railsRails 8.1・8.0・7.2 向け

rubygems.org の最新の安定版は rspec 3.13.2(2025年10月21日)・rspec-core 3.13.7(2026年11月6日)で、4.0.0.beta1 がプレリリースです。Ruby に同梱のテストの道具は minitest で、Rails の標準のテストもその上にあります。

RSpec

describe・it・expect で振る舞いを文にする。let・モック・共有の仕組みが揃う。gem を足して使う

minitest

Ruby に同梱。assert_equal のメソッド形と、describe・it の spec 形の両方で書ける

Ruby そのものの文法は、関連記事「Rubyとは?入門|基本文法・エラー原文・Pythonとの違いを実行で確認」で扱っています。次の節では、RSpec を入れて最初のファイルを作ります。

RSpecのインストールとrspec --init(Gemfile・.rspec・spec_helper)

この節では、RSpec を入れて、テストを置くフォルダと設定ファイルを作る手順が分かります。

1

Gemfile に rspec を書く

プロジェクトの Gemfile の test グループに gem "rspec", "~> 3.13" を足す。1つだけ試すなら gem install rspec でも入る。

~> 3.13 は 3.13 以上 4.0 未満

2

bundle install で入れる

Gemfile.lock に、入った rspec-core・rspec-expectations・rspec-mocks の版が書かれる。

チームで同じ版をそろえられる

3

bundle exec rspec --init

.rspec と spec/spec_helper.rb ができる。すでに .rspec があると、出力は「exist .rspec」になる。

公式の説明では create .rspec と出る

4

spec/ に *_spec.rb を置いて実行

bundle exec rspec で spec/ の下の *_spec.rb が全部動く。

ファイル名の最後は _spec.rb

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

group :test do
  gem "rspec", "~> 3.13"
end

.rspec の中身は、rspec-core のひな形のとおり --require spec_helper の1行で、毎回 spec_helper.rb が先に読まれます。spec_helper.rb の推奨の設定は =begin〜=end で囲まれていて、外すと有効になります。囲みには、実行順をばらばらにする config.order = :random や、RSpec. の無い describe を禁止する config.disable_monkey_patching! があります。

ファイル役割
.rspec毎回付ける
オプション
spec/spec_helper.rb全体の設定
spec/*_spec.rbテストを書く
ファイル
spec/support/共有の部品を
置く場所
lib/テストされる
コード

RSpec 4 に備えて確かめること

RSpec 4.0.0.beta1 の Changelog にある変更のうち、今のテストで先に直せるものです。

  • 1一番外を RSpec.describe で書いているかルートや Module に出ていた describe などは 4.0.0.beta1 で削除
  • 2should を使っていないか1行の it { should … } も含めて本体から切り出された
  • 3順番を変えても通るか既定の順番が random に変わる。今から --order random で確かめる
  • 4Ruby 3.0 以上かRuby 3.0 未満は対応外
  • 5:if・:unless のメタデータに頼っていないか特別な扱いが削除

上の2つの設定を有効にすると、1と3を 3.13 のうちに確かめられます。Gemfile を "~> 3.13" にしておけば、試験版の 4.0 に意図せず上がりません。

rspec コマンドが見つからないときは bundle exec rspec にするか、Ruby の版の切り替えを確かめます。切り替えは関連記事「rbenvの使い方|インストール・Rubyのバージョン切り替えとエラーの直し方」で扱っています。次の節では、最初のテストを書きます。

RSpecの書き方の基本|describe・it・expect

この節では、describe・it・expect の役割と、1つの it に何を書くかが分かります。

describe は「何のテストか」のまとまり、it は「どう振る舞うか」の1件(example)、expect は「結果がこうなるはず」の確かめです。 この記事では、100円ごとにポイントが付き、ゴールド会員は2倍になる PointCard クラスを例にします。

# lib/point_card.rb(テストされるコード)
class PointCard
  RATES = { normal: 1, gold: 2 }.freeze

  attr_reader :rank

  def initialize(rank: :normal)
    raise ArgumentError, "unknown rank: #{rank}" unless RATES.key?(rank)
    @rank = rank
  end

  def points(amount)
    (amount / 100) * RATES[@rank]
  end

  def gold?
    @rank == :gold
  end
end
# spec/point_card_spec.rb
require_relative "../lib/point_card"

RSpec.describe PointCard do
  describe "#points" do
    it "100円ごとに1pt付く" do
      expect(PointCard.new.points(1280)).to eq 12
    end

    it "100円未満は0pt" do
      expect(PointCard.new.points(99)).to eq 0
    end
  end
end

eq 12 の部分をマッチャと呼び、否定は not_to です。describe は入れ子にでき、外側にクラス、内側に "#points"(インスタンスメソッド)や ".create"(クラスメソッド)を書きます。

  • 1つの it に1つの振る舞い:expect を並べると最初の失敗で残りが動かない。関連する値をまとめて見るときだけ並べる。
  • 以前の should 構文:x.should eq 12 は以前の書き方。expect 構文は RSpec 2.11 で入り、3.13 でも両方使えるが、should を明示して有効にしないと非推奨の警告が出る。今の公式の例は expect 構文で書かれている。

最後の行には、公式の例では「3 examples, 0 failures」の形で件数が出ます。次の節では、expect の後ろに書くマッチャを一覧にします。

マッチャの早見表(eq・include・raise_error・changeなど)

この節では、よく使うマッチャと、eq・eql・equal の違いを動かした出力で確かめられます。

マッチャ成功する条件
eq(12)== で等しい
eql(12)eql? で等しい
(型も同じ)
equal(x)
be(x)
同じオブジェクト
be true
be_nil
true そのもの
nil
be_truthy
be_falsey
nil・false 以外
nil か false
be > 3
be_between(1, 5)
大小・範囲
be_within(0.01)
.of(0.3)
誤差の範囲で
等しい
include("gold")要素・キー・
文字列を含む
contain_exactly(1, 2)
match_array
順番を問わず
要素が同じ
match(/\d+pt/)正規表現に合う
be_goldgold? が真
(述語マッチャ)
respond_to(:points)メソッドを持つ
have_attributes(
rank: :gold)
属性の値が一致
raise_error(
ArgumentError)
例外を出す
change { a.size }
.by(1)
前後で値が
変わる
output("ok")
.to_stdout
標準出力に書く

raise_error・change・output は処理を確かめるので expect { ... } の波かっこで書き、expect { PointCard.new(rank: :silver) }.to raise_error(ArgumentError, /unknown rank/) のようにクラスとメッセージを指定できます。

eq・eql・equal(be)の違いを Ruby で確かめる

eq・eql・equal は、それぞれ Ruby の ==・eql?・equal? で比べます(公式の説明のとおり)。Ruby 3.3.6 で同じ比べを動かしました。

# equality.rb
pairs = [
  ["1, 1.0", 1, 1.0],
  [%q("pt", "pt"), "pt", "pt"],
  [":gold, :gold", :gold, :gold],
  ["[1, 2], [1, 2]", [1, 2], [1, 2]],
]
puts "a, b                ==     eql?   equal?"
pairs.each do |label, a, b|
  puts format("%-18s  %-6s %-6s %-6s", label, a == b, a.eql?(b), a.equal?(b))
end
$ ruby equality.rb
a, b                ==     eql?   equal?
1, 1.0              true   false  false 
"pt", "pt"          true   true   false 
:gold, :gold        true   true   true  
[1, 2], [1, 2]      true   true   false 

ふつうは eq、同じオブジェクトかを見るときだけ be(equal)です。 1 と 1.0 は eq で通り eql で落ちます。同じ中身の文字列や配列も別に作れば be で落ち、シンボルは be でも通りました。include の付く書き方はこのマッチャのほかに config.include と include_context があり、使い回しの節で扱います。次の節では、条件ごとに分ける context と before を見ます。

context と before で条件ごとに分ける

この節では、describe と context の違いと、before が動く順番が分かります。

context は describe の別名で、「〜のとき」という条件のまとまりに使います。 動きは同じで、対象と条件を見分けるために使い分けます。

RSpec.describe PointCard do
  describe "#points" do
    context "通常会員のとき" do
      it "100円ごとに1pt" do
        expect(PointCard.new.points(1280)).to eq 12
      end
    end

    context "ゴールド会員のとき" do
      before do
        @card = PointCard.new(rank: :gold)
      end

      it "2倍になる" do
        expect(@card.points(1280)).to eq 24
      end

      it "gold? が true" do
        expect(@card.gold?).to be true
      end
    end
  end
end

before は各 it の前に、外側から順に動き、it のあとに after が動きます。

書き方動くとき
before
before(:example)
各 it の前に毎回
(:each も同じ)
before(:context)最初に1回
(:all も同じ)
after各 it のあと
(失敗しても動く)
aroundit の前後を
包む
config
.before(:suite)
全体の最初に1回
(spec_helper.rb)

before(:context) で作ったものは it の間で共有され、ある it の変更が次に残るので、データの準備はふつう before に書きます。次の節では、名前を付けて準備する let を見ます。

let と let!・subject の使い分け

この節では、let・let!・before・subject のどれで準備を書くかが分かります。

let は名前を付けた準備で、初めて呼ばれたときに1回だけ作られます。 公式の説明は「let is lazy-evaluated」(遅延評価)です。同じ it の中では作った値を使い回し、次の it では作り直します。

RSpec.describe PointCard do
  let(:rank) { :normal }
  let(:card) { PointCard.new(rank: rank) }
  subject { card.points(1280) }

  it { is_expected.to eq 12 }

  context "ゴールド会員のとき" do
    let(:rank) { :gold }

    it { is_expected.to eq 24 }
  end
end

内側で let(:rank) を書き直すと、外側の card もその値で作られます。subject はテストの主役をまとめる let で、is_expected は公式の説明どおり expect(subject) の短い書き方です。1行の形では、説明の文がマッチャから自動で作られます。describe にクラスを渡したまま subject を書かないと、公式の説明どおり、そのクラスのインスタンスが subject になります。

let(遅延)

呼ばれたときに作る。使わない it では作られない。ふだんはこちら

let!(先に作る)

各 it の前に必ず作る。DB に先に入れておきたいデータ向け

let で作るだけのデータは、使わない it では作られません(順番の節の[B]の出力のとおり)。DB に先に入れておきたいときなど、作ること自体に意味があるなら let! にします。

重複を減らしすぎる

避けたい形let・subject・shared を重ねて、it だけを読んでも何を確かめているか分からない
→
代わりに多少の重複は残し、it の近くに入力と期待値が見える形にする

テストは失敗したときに読まれるもの。読みやすさを先に置く

次の節では、before と let が実際にどの順で動くかを、手元の minitest で確かめます。

let・beforeが動く順番(minitestで動かして確認)

この節では、before・let・after が1つの it の中でどの順に動くかを、動かした出力で確かめられます。

minitest の spec 形にも describe・before・after・let があります。それぞれに puts を入れ、let を2回使う it[A]と使わない it[B]を動かしました。

# spec/order_spec.rb
require "minitest/autorun"

describe "実行の順番" do
  before { puts "  1 外側の before" }
  after  { puts "  5 after" }
  let(:card) { puts "  3 let(:card) を評価"; :card }

  describe "内側" do
    before { puts "  2 内側の before" }

    it "card を2回使う" do
      puts "[A] card を2回使う"
      card
      card
      puts "  4 it の本体の終わり"
    end

    it "card を使わない" do
      puts "[B] card を使わない"
    end
  end
end
$ ruby spec/order_spec.rb --seed 7
Run options: --seed 7

# Running:

  1 外側の before
  2 内側の before
[A] card を2回使う
  3 let(:card) を評価
  4 it の本体の終わり
  5 after
.  1 外側の before
  2 内側の before
[B] card を使わない
  5 after
.

Finished in 0.004518s, 442.6555 runs/s, 0.0000 assertions/s.

2 runs, 0 assertions, 0 failures, 0 errors, 0 skips
before・let・after の順番(出力から) [A]card を2回使う [B]使わない 1 外側の before 2 内側の before it の本体に入る 3 let を評価(1回) 2回呼んでも1回だけ 4 本体の終わり 5 after 1 外側の before 2 内側の before it の本体 let は評価されない (3 の行が出ない) 5 after

1before は外側から

どちらの it でも「1 外側」「2 内側」の順に出た。

2let は呼んだ時に1回

[A]で card を2回呼んでも「3 let を評価」は1行だけ。本体に入ってから評価された。

3使わなければ作られない

[B]では 3 の行が出なかった。先に作るなら let!。

minitest には let! が無いので、先に作るなら before の中で let を呼びます。次の節では、つながる相手を偽物に置き換えるモックを見ます。

モックとスタブ|double・allow・receive・instance_double

この節では、テストしたいクラスがつながる相手を、偽物に置き換える書き方が分かります。

double は偽物、allow は「呼ばれたらこう返す」(スタブ)、expect(...).to receive は「必ず呼ばれるはず」(モック)です。 支払いのポイントを通知の部品(notifier)に送る Checkout クラスで見ます。

class Checkout
  def initialize(card, notifier)
    @card = card
    @notifier = notifier
  end

  def pay(amount)
    pt = @card.points(amount)
    @notifier.notify("#{pt}pt")
    pt
  end
end
RSpec.describe Checkout do
  let(:card) { PointCard.new(rank: :gold) }

  it "notify に獲得ポイントを渡す(モック)" do
    notifier = double("notifier")
    expect(notifier).to receive(:notify).with("24pt")
    Checkout.new(card, notifier).pay(1280)
  end

  it "points の戻り値を差し替える(スタブ)" do
    notifier = double("notifier", notify: nil)
    allow(card).to receive(:points).and_return(999)
    expect(Checkout.new(card, notifier).pay(1280)).to eq 999
  end

  it "呼ばれたかをあとで確かめる(spy)" do
    notifier = spy("notifier")
    Checkout.new(card, notifier).pay(1280)
    expect(notifier).to have_received(:notify).with("24pt").once
  end

  it "実在するメソッドだけ許す(instance_double)" do
    notifier = instance_double("Notifier", notify: nil)
    Checkout.new(card, notifier).pay(1280)
  end
end
書き方意味
double("名前")何も知らない偽物。
許していない
メソッドは失敗
double("n",
notify: nil)
スタブ付きで作る
allow(x)
.to receive(:m)
.and_return(1)
呼ばれたら 1 を返す
(呼ばれなくてよい)
expect(x)
.to receive(:m)
呼ばれないと失敗
(it の終わりに確認)
.with("24pt")引数を指定
.once・.twice
.exactly(3).times
呼ばれる回数
spy("名前")
have_received(:m)
何でも受け、
あとで確かめる
instance_double(
"Cls")
そのクラスの
インスタンス
メソッドだけ許す
class_double("Cls")
object_double(obj)
クラスメソッド・
実物を手本にする

instance_double は、手本のクラスが読み込まれていれば、無いメソッドや引数の数の違いを失敗にします。 公式の例の失敗メッセージは「ConsoleNotifier class does not implement the instance method:」と「Wrong number of arguments.」です。double は本物のクラスを見ないので、本物から notify が消えても通り続けます。相手のクラスがあるなら instance_double を選びます。

spy と have_received は「準備・実行・確認」の順に書く形で、公式の例では、呼ばれなかったときに「expected: 1 time with any arguments」「received: 0 times with any arguments」と出ます。スタブ・モック・スパイの言葉の違いは、関連記事「テストダブルとは|スタブ・モック・スパイ・フェイクの違いと使い分け」で扱っています。次の節では、ここまでの書き方を minitest で動かします。

同じテストをminitestで書いて動かす(RSpecとの対応表)

この節では、RSpec の書き方が minitest では何に当たるかを、動かした出力つきで確かめられます。先に、動かした結果をまとめます。

動かしたもの結果
マッチャ16件16件とも通った
(19 assertions)
2つの形let の書き直しが
外側に効いて 24
わざと失敗Expected・Actual
終了コード 1
モックの失敗呼ばれないと verify で
引数違いはその場で
RSpecminitest
上:spec 形
下:メソッド形
describe
context
describe
class X < Minitest::Test
itit
def test_xxx
before・afterbefore・after
setup・teardown
let・subjectlet・subject
メソッドを書く
to eq 2_(x).must_equal 2
assert_equal 2, x
not_to eq 3_(x).wont_equal 3
refute_equal 3, x
be_nilmust_be_nil
assert_nil
be_truthy
be_falsey
assert x
refute x
be > 3must_be :>, 3
assert_operator
be_withinmust_be_within_delta
assert_in_delta
includemust_include
assert_includes
matchmust_match
assert_match
raise_error_ { }.must_raise
assert_raises
double
expect…receive
Minitest::Mock
expect と verify
allow…
and_return
obj.stub(:m, 値) { }

マッチャの対応を16件まとめて動かす

表の spec 形を、minitest 5.20.0 で1件ずつ it にして動かしました。

# spec/matchers_spec.rb
require "minitest/autorun"

describe "RSpec のマッチャに当たる minitest の書き方" do
  it("eq")          { _(1 + 1).must_equal 2 }
  it("not_to eq")   { _(1 + 1).wont_equal 3 }
  it("be")          { _(:gold).must_be_same_as :gold }
  it("be_nil")      { _(nil).must_be_nil }
  it("be_truthy")   { assert "pt" }
  it("be_falsey")   { refute nil }
  it("be >")        { _(10).must_be :>, 3 }
  it("be_within")   { _(0.1 + 0.2).must_be_within_delta 0.3, 0.001 }
  it("include")     { _(%w[normal gold]).must_include "gold" }
  it("match")       { _("24pt").must_match(/\A\d+pt\z/) }
  it("be_empty")    { _([]).must_be_empty }
  it("be_a")        { _(24).must_be_kind_of Integer }
  it("respond_to")  { _("pt").must_respond_to :upcase }
  it("raise_error") { _ { Integer("x") }.must_raise ArgumentError }
  it("output")      { _ { print "ok" }.must_output "ok" }
  it("contain_exactly") { _(%w[b a].sort).must_equal %w[a b] }
end
$ ruby spec/matchers_spec.rb --seed 5
Run options: --seed 5

# Running:

................

Finished in 0.001181s, 13543.9875 runs/s, 16083.4851 assertions/s.

16 runs, 19 assertions, 0 failures, 0 errors, 0 skips

16件すべて通りました。contain_exactly に当たるものは無いので、並べ替えてから比べています。assertions が runs より19対16と多いのは、must_include・must_be_empty・must_match が中で2回ずつ数えるためです(1件ずつ動かして確かめました)。

PointCard のテストを2つの形で動かす

# test/point_card_test.rb(メソッド形)
require "minitest/autorun"
require "point_card"

class PointCardTest < Minitest::Test
  def setup
    @card = PointCard.new
  end

  def test_points_normal
    assert_equal 12, @card.points(1280)
  end

  def test_points_gold
    assert_equal 24, PointCard.new(rank: :gold).points(1280)
  end

  def test_gold_predicate
    refute @card.gold?
  end

  def test_unknown_rank
    e = assert_raises(ArgumentError) { PointCard.new(rank: :silver) }
    assert_match(/unknown rank/, e.message)
  end
end
# spec/point_card_minitest_spec.rb(minitest の spec 形)
require "minitest/autorun"
require "point_card"

describe PointCard do
  let(:rank) { :normal }
  let(:card) { PointCard.new(rank: rank) }

  describe "#points" do
    it "100円ごとに1pt" do
      _(card.points(1280)).must_equal 12
    end

    describe "ゴールド会員" do
      let(:rank) { :gold }

      it "2倍になる" do
        _(card.points(1280)).must_equal 24
      end
    end
  end

  it "不明なランクは ArgumentError" do
    _ { PointCard.new(rank: :silver) }.must_raise ArgumentError
  end
end
$ ruby -Ilib test/point_card_test.rb --seed 1234
Run options: --seed 1234

# Running:

....

Finished in 0.000920s, 4348.9701 runs/s, 6523.4551 assertions/s.

4 runs, 6 assertions, 0 failures, 0 errors, 0 skips
$ ruby -Ilib spec/point_card_minitest_spec.rb --seed 1234 -v
Run options: --seed 1234 -v

# Running:

PointCard::#points::ゴールド会員#test_0001_2倍になる = 0.00 s = .
PointCard#test_0001_不明なランクは ArgumentError = 0.00 s = .
PointCard::#points#test_0001_100円ごとに1pt = 0.00 s = .

Finished in 0.000900s, 3334.1928 runs/s, 3334.1928 assertions/s.

3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

spec 形の it は、中で test_0001_説明 というメソッドに変わることが -v の出力から分かります。内側で書き直した let(:rank) は外側の card に効いて 24 になりました。

失敗したときの出力

# spec/fail_spec.rb
require "minitest/autorun"
require "point_card"

describe PointCard do
  it "1280円で13pt(わざと間違えた期待値)" do
    _(PointCard.new.points(1280)).must_equal 13
  end

  it "配列の中身(順番違い)" do
    _(%w[a b c]).must_equal %w[c b a]
  end
end
$ ruby -Ilib spec/fail_spec.rb --seed 1; echo "exit=$?"
Run options: --seed 1

# Running:

FF

Finished in 0.000820s, 2440.1016 runs/s, 2440.1016 assertions/s.

  1) Failure:
PointCard#test_0001_1280円で13pt(わざと間違えた期待値) [spec/fail_spec.rb:7]:
Expected: 13
  Actual: 12

  2) Failure:
PointCard#test_0002_配列の中身(順番違い) [spec/fail_spec.rb:11]:
Expected: ["c", "b", "a"]
  Actual: ["a", "b", "c"]

2 runs, 2 assertions, 2 failures, 0 errors, 0 skips
exit=1

失敗すると終了コードは 1 になり、CI で止まります。2件目は RSpec なら contain_exactly で通る比べで、順番まで見る must_equal では落ちます。

モックとスタブを minitest で動かす

# spec/checkout_spec.rb
require "minitest/autorun"
require "minitest/mock"
require "point_card"

class Checkout
  def initialize(card, notifier)
    @card = card
    @notifier = notifier
  end

  def pay(amount)
    pt = @card.points(amount)
    @notifier.notify("#{pt}pt")
    pt
  end
end

describe Checkout do
  let(:card) { PointCard.new(rank: :gold) }

  it "notify に獲得ポイントを渡す(モック)" do
    notifier = Minitest::Mock.new
    notifier.expect(:notify, nil, ["24pt"])
    _(Checkout.new(card, notifier).pay(1280)).must_equal 24
    notifier.verify
  end

  it "points の戻り値を差し替える(スタブ)" do
    notifier = Minitest::Mock.new
    notifier.expect(:notify, nil, ["999pt"])
    card.stub(:points, 999) do
      _(Checkout.new(card, notifier).pay(1280)).must_equal 999
    end
    notifier.verify
  end

  it "引数が違うと失敗する(わざと)" do
    notifier = Minitest::Mock.new
    notifier.expect(:notify, nil, ["10pt"])
    Checkout.new(card, notifier).pay(1280)
    notifier.verify
  end

  it "呼ばれないと verify で失敗する(わざと)" do
    notifier = Minitest::Mock.new
    notifier.expect(:notify, nil, ["24pt"])
    notifier.verify
  end
end
$ ruby -Ilib spec/checkout_spec.rb --seed 3; echo "exit=$?"
Run options: --seed 3

# Running:

E..E

Finished in 0.000885s, 4517.2780 runs/s, 2258.6390 assertions/s.

  1) Error:
Checkout#test_0004_呼ばれないと verify で失敗する(わざと):
MockExpectationError: expected notify("24pt") => nil
    spec/checkout_spec.rb:48:in `block (2 levels) in <main>'

  2) Error:
Checkout#test_0003_引数が違うと失敗する(わざと):
MockExpectationError: mocked method :notify called with unexpected arguments ["24pt"]
    spec/checkout_spec.rb:14:in `pay'
    spec/checkout_spec.rb:41:in `block (2 levels) in <main>'

4 runs, 2 assertions, 0 failures, 2 errors, 0 skips
exit=1

1verify を書き忘れない

「呼ばれなかった」は verify で初めて検出された。RSpec の expect…receive は it の終わりに自動で確かめる。

2引数違いはその場で落ちる

「24pt」で呼ばれると、pay の14行目でその場で MockExpectationError になった。

3stub はブロックの間だけ

card.stub(:points, 999) はブロックを抜けると元に戻る。RSpec の allow は it の終わりまで効く。

rspec-mocks の公式には minitest と組み合わせる方法(Integrating with Minitest)も載っています。Python の pytest や Java の JUnit での書き方と比べたいときは、関連記事「単体テストと結合テストの違い|pytestの実例と実行結果で比較」「JUnitの使い方|単体テストの書き方と観点【JUnit 5・6】」で扱っています。次の節では、rspec コマンドで一部だけ動かす方法を見ます。

rspecコマンドの実行オプション(行番号・タグ・失敗だけ・順番)

この節では、一部のテストだけを動かすオプションと、ランダムな順番の再現のしかたが分かります。

コマンド動くもの
bundle exec rspecspec/ の
*_spec.rb を全部
rspec
spec/a_spec.rb
そのファイル
rspec
spec/a_spec.rb:12
12行目を含む
example
-e "ゴールド"説明にその語を
含む example
--tag focusfocus: true
を付けたもの
-f d
--format
documentation
説明の文を
木の形で出す
--only-failures前回の失敗だけ
--next-failure失敗だけを順に、
最初の失敗で止める
--fail-fast最初の失敗で止める
--order randomばらばらの順番
--seed 1234同じ並びを再現
--bisect順番で落ちる
組み合わせを絞る

--only-failures は、spec_helper.rb に config.example_status_persistence_file_path = "examples.txt" を書いてから使います。書かずに使うと「To use --only-failures, you must first set config.example_status_persistence_file_path.」と出ます。rspec --init の spec_helper.rb の囲みにも "spec/examples.txt" で入っています。公式の説明では、--next-failure は --only-failures --fail-fast --order defined の短い書き方です。

ランダムな順番と seed(minitest で確かめる)

minitest は毎回ばらばらの順番で動かし、先頭に seed を出します。PointCardTest を seed 1 と 2 で動かし、テスト名の行を grep で取り出しました。

$ for s in 1 2; do ruby -Ilib test/point_card_test.rb --seed $s -v | grep -E "^PointCardTest|seed"; done
Run options: --seed 1 -v
PointCardTest#test_unknown_rank = 0.00 s = .
PointCardTest#test_points_normal = 0.00 s = .
PointCardTest#test_gold_predicate = 0.00 s = .
PointCardTest#test_points_gold = 0.00 s = .
Run options: --seed 2 -v
PointCardTest#test_points_normal = 0.00 s = .
PointCardTest#test_unknown_rank = 0.00 s = .
PointCardTest#test_points_gold = 0.00 s = .
PointCardTest#test_gold_predicate = 0.00 s = .

seed が変わると並びが変わります。ある順番のときだけ落ちるテストは、前のテストが残したデータに頼っている合図です。RSpec 3 でも config.order = :random を有効にするとこの形になり、出力の seed を --seed に渡すと再現できます。次の節では、テストを一時的に止める書き方を見ます。

skip・xit・pendingでテストを止めておく

この節では、直せないテストや、まだ書いていないテストの扱い方が分かります。

書き方動き・出力
(公式の例)
止める(中身は動かさない)
skip "理由"そこで止める。
理由なしは
「No reason given」
:skip => trueメタデータで
飛ばす
xit・xspecify
xexample
example を飛ばす
「Temporarily
skipped with xit」
xdescribe
xcontext
まとまりごと
飛ばす
動かすが失敗を許す
pending "理由"中身は動く。
失敗しても全体は通る。
通ると失敗扱い
まだ書かない
it "説明"
(ブロックなし)
「Not yet
implemented」
(仕様のメモ)

公式の例では、xit など3件を飛ばすと「3 examples, 0 failures, 3 pending」と出て、終了コードは 0 です。pending が「通ると失敗」なのは、直ったことを知らせるためです。次の節では、テストを使い回す仕組みを見ます。

shared_examples・shared_contextでテストを使い回す

この節では、同じ確かめを複数の場所で使う書き方と、include の付く3つの書き方の違いが分かります。

# spec/support/point_examples.rb
RSpec.shared_examples "ポイントの基本" do
  it "0円なら0pt" do
    expect(card.points(0)).to eq 0
  end
end

RSpec.shared_context "ゴールド会員" do
  let(:card) { PointCard.new(rank: :gold) }
end

# spec/point_card_spec.rb
RSpec.describe PointCard do
  context "通常会員" do
    let(:card) { PointCard.new }
    it_behaves_like "ポイントの基本"
  end

  context "ゴールド会員" do
    include_context "ゴールド会員"
    it_behaves_like "ポイントの基本"
    it { expect(card.points(1280)).to eq 24 }
  end
end
書き方何をするか
shared_examplesit の束を定義
(単独では動かない)
it_behaves_like入れ子として
取り込む
include_examples今の場所に
取り込む
shared_contextlet・before を
まとめて定義
include_contextshared_context
を取り込む
config.include Mod全 example で
メソッドを使う
include(x)含むかを
確かめるマッチャ

公式は、同じ名前のメソッドの上書きを避けたいときは it_behaves_like を勧めています。共有の定義は自動では読まれないので、require するか spec/support/ に置いて spec_helper.rb で読み込みます(フォルダを丸ごと読む形は起動が遅くなるため勧めていません)。

# spec/spec_helper.rb
require_relative "support/point_examples"

module YenHelper
  def yen(n) = n * 100
end

RSpec.configure do |config|
  config.include YenHelper
end

次の節では、Rails で RSpec を使う準備を見ます。

RailsでRSpecを使う(rspec-railsの導入とspecの種類)

この節では、Rails のアプリに rspec-rails を入れる手順と、spec の種類が分かります。

# Gemfile
group :development, :test do
  gem "rspec-rails", "~> 8.0"
end
bundle install
bin/rails generate rspec:install
bundle exec rspec

README は development と test の両方のグループに入れるよう案内しています(development に無いとジェネレーターの前に RAILS_ENV=test が要る)。rails generate rspec:install は .rspec・spec/・spec/spec_helper.rb・spec/rails_helper.rb を作ります。各 spec の先頭で require "rails_helper" と書きます。以後 rails generate model user で spec/models/user_spec.rb も一緒にでき、rails generate rspec:model user で spec だけを作れます。

rspec-rails対応する Rails
8.x8.1・8.0・7.2
7.x7.x
6.x6.1・7.0・7.1
5.x5.2・6.x
4.x5.x・6.x
spec の種類確かめること・土台
modelモデルの検証・
メソッド
(spec/models)
requestURL への応答
ActionDispatch::
IntegrationTest
systemブラウザ操作の通し
ActionDispatch::
SystemTestCase
(Rails 5.1 以降)
mailerメールの中身
ActionMailer::
TestCase
view・helper画面の部品
ActionView::
TestCase
controllerコントローラー
ActionController::
TestCase
# spec/requests/cards_spec.rb
require "rails_helper"

RSpec.describe "Cards", type: :request do
  it "一覧が200で返る" do
    get "/cards"
    expect(response).to have_http_status(:ok)
  end
end

rspec-rails 8.0.0 で最低の対応が Rails 7.2.0 になり、8.1.0(2026年11月6日)で Rails 8.1 に正式対応しました。次の節では、テストのデータを作る FactoryBot を見ます。

FactoryBot(factory_bot)でテストデータを作る・traitの使い方

この節では、テストのデータを1か所で定義して、trait で種類を切り替える書き方が分かります。

FactoryBot は、データの作り方(factory)を定義して create(:user) の1行で作れるようにする gem です。 最新は factory_bot 6.7.0(2026年11月26日・Ruby 3.1.0 以上)。Rails では factory_bot_rails、Rails なしでは factory_bot を入れます。

# spec/support/factory_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

# spec/factories/users.rb
FactoryBot.define do
  factory :user do
    name { "山田" }
    rank { "normal" }

    trait :gold do
      rank { "gold" }
    end
  end
end
user  = build(:user)               # 保存しない
gold  = create(:user, :gold)       # trait を付けて保存
named = create(:user, name: "佐藤") # 値を上書き
attrs = attributes_for(:user)      # 属性のハッシュ
stub  = build_stubbed(:user)       # 保存したように振る舞う
メソッド返すもの
build保存しない
インスタンス
create保存した
インスタンス
attributes_for属性のハッシュ
(関連は含まない)
build_stubbed保存したように
振る舞う(DB なし)

trait は属性のまとまりに名前を付けたもので、公式の説明は「Traits allow you to group attributes together」です。 create(:user, :gold) のように並べて付け、factory :gold_user, traits: [:gold] で別の factory にもできます。DB に保存しなくてよいテストは build や build_stubbed にすると、保存の処理を省けます。

Serverspec|RSpecの書き方でサーバーの状態をテストする

この節では、RSpec の書き方でサーバーの設定を確かめる Serverspec の始め方が分かります。

Serverspec は、パッケージ・サービス・ポート・ファイルの設定を RSpec で確かめる gem です。 公式の説明では、構成管理の道具を問わず使え、エージェントを入れずに手元・SSH・WinRM・Docker API などで調べます。rubygems.org の最新は 2.43.0(2025年4月24日)です。

  1. 1入れるGemfile に serverspec を足して bundle install、または gem install serverspec
  2. 2serverspec-init で質問に答える「Select OS type:」「Select a backend type:」(SSH か Exec (local) など)、Vagrant の有無、「Input target host name:」に答える
  3. 3できたファイルに確かめを書くspec/ホスト名/sample_spec.rb の隣に *_spec.rb を足すと対象になる
  4. 4rake spec で動かすホストごとは rake spec:ホスト名。sudo のパスワードを入れるなら ASK_SUDO_PASSWORD=1
作られるもの役割
spec/ホスト名/
sample_spec.rb
確かめを
書くファイル
spec/spec_helper.rb接続の方法・
ユーザーの設定
Rakefilespec:ホスト名
spec:all のタスク
.rspecrspec の
オプション

SSH で作った spec_helper.rb は、ASK_SUDO_PASSWORD があると「Enter sudo password: 」と聞き、無ければ環境変数 SUDO_PASSWORD を使います(serverspec のソースで確認)。sudo のパスワードが要るのに渡していないと「Please set sudo password to Specinfra.configuration.sudo_password.」で止まります(specinfra のソースで確認)。公式は1台ずつ動かす前提だと説明しています。

# spec/web01/nginx_spec.rb
require "spec_helper"

describe package("nginx") do
  it { should be_installed }
end

describe service("nginx") do
  it { should be_enabled }
  it { should be_running }
end

describe port(80) do
  it { should be_listening }
end

describe file("/etc/nginx/nginx.conf") do
  it { should be_file }
  it { should be_owned_by "root" }
  its(:content) { should match(/worker_processes/) }
end

describe command("nginx -t") do
  its(:exit_status) { should eq 0 }
end
リソース主なマッチャ
packagebe_installed
.with_version("1.2")
servicebe_enabled(自動起動)
be_running
portbe_listening
.with("udp")
filebe_file・be_directory
be_mode 600
be_owned_by
be_grouped_into
be_readable.by_user
its(:content)
userexist
belong_to_group
have_uid
groupexist
have_gid
commandits(:stdout)
its(:exit_status)
hostbe_resolvable
.by("hosts")

公式の例は subject に対する should のワンライナー it { should ... } で書かれていますが、Resource Types のページは expect の形でも動くと説明しています。serverspec 2.43.0 は rspec の 3 系(~> 3.0)に依存するので、RSpec 3.13 の上で使います。新しく書くなら it { is_expected.to be_installed } の形にそろえると、ふつうの RSpec のテストと同じ書き方になります。

よくある質問

この節では、RSpec を書き始めるときによく聞かれることに短く答えます。

Q. RSpec と minitest はどちらを使えばいいですか?
既存のテストに合わせます。新しく始めるなら、同梱の minitest か、let・モック・共有が揃う RSpec かで選びます。対応表のとおり、書き方は1対1でほぼ置き換えられます。

Q. describe と context の違いは?
動きは同じで、context は describe の別名です。describe に対象、context に条件(〜のとき)を書きます。

Q. let と let! と before の違いは?
let は呼ばれたときに1回作り、let! は各 it の前に必ず作り、before は名前なしで準備を動かします。

Q. double と instance_double の違いは?
double は何のクラスの偽物かを知りません。instance_double は手本のクラスを知っていて、無いメソッドや引数の数の違いを失敗にします。

Q. allow と expect(...).to receive の違いは?
allow は「呼ばれたらこう返す」で、呼ばれなくても失敗しません。expect…receive は「呼ばれるはず」で、呼ばれないと失敗します。

Q. RSpec.describe と describe のどちらで書けばいいですか?
RSpec.describe です。RSpec 4.0.0.beta1 ではルートの describe が削除され、3.13 でも disable_monkey_patching! を有効にすると RSpec. が要ります。

Q. RSpec 4 はもう使えますか?
2026年12月1日の時点では 4.0.0.beta1(試験版)で、安定版は 3.13 系です。

Q. Rails の fixtures と FactoryBot はどう違いますか?
fixtures は YAML のデータを読み込む Rails 標準の仕組み、FactoryBot はテストごとに必要な分だけ作る gem です。

Q. Serverspec は RSpec と別に覚えるものですか?
describe・it はそのまま RSpec で、package・service などのリソースとマッチャが加わる形です。

まとめ

この節では、記事の要点を5つにまとめます。

  • RSpec は describe(対象)・context(条件)・it(振る舞い)・expect(確かめ)で書く。安定版は 3.13 系、4.0.0.beta1 が試験版。
  • 準備は let・let!・before・subject で書き分ける。minitest で動かすと、let は使わない it では作られなかった。
  • マッチャはふつう eq。1 と 1.0 は eq で通り eql で落ち、同じオブジェクトかは be で見る。
  • 部品の置き換えは allow(スタブ)と expect…receive(モック)。相手のクラスがあれば instance_double を使う。
  • Rails は rspec-rails 8.x、データは FactoryBot の trait、サーバーは Serverspec で同じ書き方が使える。

参考・出典

確認日はいずれも 2026年12月1日です。

  • RSpec 公式サイト:https://rspec.info/
  • RSpec 3.13 のドキュメント(--init・let and let!・One-liner syntax・Shared examples・Pending and skipped examples・Using the --only-failures option・Built in matchers・Mocks):https://rspec.info/features/3-13/
  • RSpec Mocks 3.13「Using an instance double」:https://rspec.info/features/3-13/rspec-mocks/verifying-doubles/instance-doubles/
  • RSpec Mocks 3.13「Spies」:https://rspec.info/features/3-13/rspec-mocks/basics/spies/
  • rspec-core Changelog(4.0.0.beta1・3.13.7):https://github.com/rspec/rspec/blob/main/rspec-core/Changelog.md
  • rspec-core の .rspec のひな形:https://github.com/rspec/rspec-core/blob/main/lib/rspec/core/project_initializer/.rspec
  • rubygems.org「rspec」「rspec-core」「rspec-rails」「factory_bot」「serverspec」:https://rubygems.org/
  • rspec-rails README・Changelog:https://github.com/rspec/rspec-rails
  • factory_bot「Setup」「Build strategies」「Traits」:https://thoughtbot.github.io/factory_bot/
  • Serverspec 公式サイト・Resource Types:https://serverspec.org/ ・ https://serverspec.org/resource_types.html
  • serverspec のソース(setup.rb):https://github.com/mizzy/serverspec/blob/master/lib/serverspec/setup.rb
  • minitest のドキュメント:https://docs.seattlerb.org/minitest/

本記事の内容は、ご自由にお使いください。
ご利用の際は、出典として本ページへのリンクを記載いただけますようお願いします。

(記載例)出典:株式会社RJC「RSpecの書き方入門|マッチャ・モック早見表とminitest対応表」

株式会社RJC ― SI事業・SES事業・AI駆動開発。RJCは一緒に成長を楽しめる会社です。

WE ARE HIRING

RJCで一緒に開発しながら、
成長を楽しみませんか?

RJCは、Web・モバイル・AIを活用した開発プロジェクトで、テックリードやPM・PMOも活躍するシステム開発会社です。会社を知る、待遇を確かめる、話を聞いてみる。気になるところ見てみてください!

  • 127日年間休日
  • 12時間平均残業時間
  • 毎日ガチャ遊びココロも大切にする福利厚生。アマギフなどの賞品ラインナップ!

ほかにも、チケットレストラン、書籍読み放題、2年ごとの慰労報奨(休暇 or 金一封)、11期連続の黒字決算。

ABOUT RJC RJCがどんな会社か知る 考え方、研修、働き方、福利厚生、社員の前職まで。RJCのことが丸わかり! RJC丸わかりページへ JOB DESCRIPTION 仕事内容・待遇を見てみる 仕事内容、給与・待遇、選考の流れ。経験者も未経験も!応募前に知りたいこと、まとめました! 募集要項を見る ENTRY エントリーする エントリーは1〜2分・履歴書不要です。まずは話を聞いてみたい、という方でも歓迎です! エントリーフォームへ

成長のヒミツ、 ぜんぶ丸わかり