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-15

記事概要

Ruby on Railsのコントローラー用単体テストファイルについて、まとめる

前提

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

基本情報

ファイルパス

spec/requests/[コントローラー名]_spec.rb

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

コントローラー名_spec.rb

describe コントローラー名Controller, type: :request do
  describe '[HTTPメソッド #アクション名]' do
    it '[テストケース]' do 
      # テストケースに合わせたテストコードを記述
    end
    it '[テストケース]' do 
      # テストケースに合わせたテストコードを記述
    end
  end
end
tweets_spec.rb
describe TweetsController, type: :request do
  describe 'GET #index' do
    it 'indexアクションにリクエストすると正常にレスポンスが返ってくる' do 
      # テストケースに合わせたテストコードを記述
    end
    it 'indexアクションにリクエストするとレスポンスに投稿済みのツイートのテキストが存在する' do 
      # テストケースに合わせたテストコードを記述
    end
  end

  describe 'GET #show' do
    it 'showアクションにリクエストすると正常にレスポンスが返ってくる' do 
      # テストケースに合わせたテストコードを記述
    end
    it 'showアクションにリクエストするとレスポンスに投稿済みのツイートのテキストが存在する' do 
      # テストケースに合わせたテストコードを記述
    end
  end
end

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

  • FactoryBot(Gem)を使用する
    user_spec.rb
    RSpec.describe User, type: :model do
      before do
        # インスタンス生成
        @user = FactoryBot.create(:user)
        
        # Active Storageが紐づいている場合、sleepを入れる
        sleep 0.1 
      end
      
      # 省略
      it '[テストケース]' do
        # before処理実行後に処理
      end
      # 省略
    end
    
  • FactoryBot(Gem)を使用しない
    user_spec.rb
    RSpec.describe User, type: :model do
      # 省略
      it '[テストケース]' do
        # インスタンス生成
        user = User.new(nickname: 'test', 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?