記事概要
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