やる気がストロングZERO

やる気のストロングスタイル

【Rails】RSpecの使い方メモ

参考:
GitHub - rspec/rspec-rails: RSpec for Rails-3+
RSpec Expectations 3.8 - RSpec Expectations - RSpec - Relish

インストール

Gemfileに追記

# Run against the latest stable release
group :development, :test do
  gem 'rspec-rails', '~> 3.8'
end

bundle installを実行してインストール

bundle update rspec-railsを実行して初期化

model用RSpec

コマンドでRSpec用ファイル作成

rails generate rspec:model user

テスト記述サンプル

Dogモデルをテストすると仮定。
dob.nameにはunique indexが貼られているとする

require 'rails_helper'

RSpec.describe Dog, type: :model do
  context "存在するdogを取得" do
    it "取得できる" do
      dog = Dog.find_by(name: "pochi")
      expect(dog).to be_an_instance_of(Dog)
    end
  end

  context "存在しないdogを取得しようとした場合" do
    it "nilが取得される" do
      dog = Dog.find_by(name: "bobobobo")
      expect(dog).to be_nil
    end
  end

  context "nameが重複しないdogを保存しようとした場合" do
    it "保存できる" do
      dog = Dog.new(name: "hachi")
      expect(dog.save).to be true
    end
  end

  context "nameが重複するdogを保存しようとした場合" do
    it "例外が発生して保存できない" do
      dog = Dog.new(name: "pochi")
      expect{ Dog.save }.to raise_error(ActiveRecord::RecordNotUnique)
    end
  end
end

実行

bundle exec rspec

マッチャー一覧

Built in matchers - RSpec Expectations - RSpec - Relish