🧪

RSpec

BDD(振る舞い駆動開発)テストフレームワーク

RSpecはRuby/Railsで最も広く使われているテストフレームワークです。

RSpec.describe Post, type: :model do
  describe 'validations' do
    it 'titleが必要' do
      post = Post.new(title: nil)
      expect(post).not_to be_valid
      expect(post.errors[:title]).to include("can't be blank")
    end
  end

  describe '#published?' do
    context 'statusがpublishedの時' do
      it 'trueを返す' do
        post = Post.new(status: 'published')
        expect(post.published?).to be true
      end
    end
  end
end

テスト種類:

  • Model Spec — モデルロジック、バリデーション、関連

  • Request Spec — HTTPリクエスト/レスポンス(Controllerテストの代替)

  • System Spec — ブラウザシミュレーション(Capybara)

  • Mailer Spec — メール送信

  • Job Spec — バックグラウンドジョブ

キーポイント

1

Gemfileにrspec-railsを追加 → rails generate rspec:install

2

spec/ディレクトリにテストファイル作成(_spec.rb接尾辞)

3

describe「対象」/ context「条件」/ it「期待動作」構造で作成

4

expect(actual).to eq(expected) — 検証(matcher)

5

let(:変数) { 値 } — lazy evaluation変数定義

6

before { 設定 } — 各テスト前に実行(setup)

メリット

  • 自然言語に近い文法で可読性が良い
  • Railsの全レイヤーをテスト可能
  • 豊富なMatcherライブラリ
  • コミュニティが大きく資料が豊富

デメリット

  • 学習曲線(describe/context/it、let、subject等)
  • 大規模テストスイートは実行時間が長くなる
  • Minitestに比べ設定が複雑
  • 過度なmock/stubは脆弱なテストを引き起こす

ユースケース

Modelバリデーションテスト APIエンドポイントテスト(Request Spec) Service Object単体テスト 認証/権限テスト