0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】[モデル名]_spec.rbについて

Last updated at Posted at 2025-05-06

記事概要

Ruby on Railsのモデル用単体テストファイルについて、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している
  • アプリにRSpecをインストールしている
  • RSpecの設定が完了している

基本情報

ファイルパス

spec/models/[モデル名]_spec.rb

まとめ(テストケース整理)

モデル名_spec.rb
RSpec.describe [モデル名], type: :model do
  describe '[機能名]' do
    context '[条件]' do
      it '[テストケース]' do
        # テストケースに合わせたテストコードを記述
      end
    end
    context '[条件]' do
      it '[テストケース]' do
        # テストケースに合わせたテストコードを記述
      end
    end
  end
end
user_spec.rb
RSpec.describe User, type: :model do
  describe 'ユーザー新規登録' do
    context '新規登録できるとき' do
      it 'すべてのカラムに値が存在すれば登録できる' do
        # テストケース[nicknameが空では登録できない]に合わせたテストコードを記述
      end
    end
    context '新規登録できないとき' do
      it 'nicknameが空では登録できない' do
        # テストケース[nicknameが空では登録できない]に合わせたテストコードを記述
      end
      it 'emailが空では登録できない' do
        # テストケース[emailが空では登録できない]に合わせたテストコードを記述
      end
    end
  end
end

まとめ(インスタンス生成)

  • FactoryBot(Gem)を使用する
    user_spec.rb
    RSpec.describe User, type: :model do
      before do
        # インスタンス生成
        @user = FactoryBot.build(:user)
      end
      
      # 省略
      it '[テストケース]' do
        # before処理実行後に処理
      end
      # 省略
    end
    
  • FactoryBot(Gem)を使用しない
    user_spec.rb
    RSpec.describe User, type: :model do
      # 省略
      it '[テストケース]' do
        # インスタンス生成
        user = User.new(nickname: '', email: 'test@example', password: '000000', password_confirmation: '000000')
        
        # 処理
      end
      # 省略
    end
    

RSpec

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?