1
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-16

記事概要

Ruby on Railsの結合テストファイルについて、まとめる

前提

  • Ruby on Railsでアプリケーションを作成している
  • アプリにCapybaraをインストールしている

基本情報

ファイルパス

spec/system/[モデル名の複数形]_spec.rb

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

モデル名の複数形_spec.rb
RSpec.describe '[処理名]', type: :system do
  context '[条件]' do 
    it '[テストケース]' do
      # テストケースに合わせたテストコードを記述
    end
  end
  context '[条件]' do
    it '[テストケース]' do
      # テストケースに合わせたテストコードを記述
    end
  end
end
users_spec.rb
RSpec.describe 'ユーザー新規登録', type: :system do
  context 'ユーザー新規登録ができるとき' do 
    it '正しい情報を入力すればユーザー新規登録ができてトップページに移動する' do
      # トップページに移動する
      # トップページにサインアップページへ遷移するボタンがあることを確認する
      # 新規登録ページへ移動する
      # ユーザー情報を入力する
      # サインアップボタンを押すとユーザーモデルのカウントが1上がることを確認する
      # トップページへ遷移することを確認する
      # カーソルを合わせるとログアウトボタンが表示されることを確認する
      # サインアップページへ遷移するボタンや、ログインページへ遷移するボタンが表示されていないことを確認する
    end
  end
  context 'ユーザー新規登録ができないとき' do
    it '誤った情報ではユーザー新規登録ができずに新規登録ページへ戻ってくる' do
      # トップページに移動する
      # トップページにサインアップページへ遷移するボタンがあることを確認する
      # 新規登録ページへ移動する
      # ユーザー情報を入力する
      # サインアップボタンを押してもユーザーモデルのカウントは上がらないことを確認する
      # 新規登録ページへ戻されることを確認する
    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: 'test', email: 'test@example', password: '000000', password_confirmation: '000000')
        
        # 処理
      end
      # 省略
    end
    
1
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
1
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?