記事概要
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: 'test', email: 'test@example', password: '000000', password_confirmation: '000000') # 処理 end # 省略 end
まとめ(DBデータ登録)
- pry-railsでコンソールを起動する
- 作成したデータ(インスタンス)がDBに保存されるかどうかを、validメソッドで確認する
- <異常系の場合のみ> ターミナル.appでエラーメッセージを確認
[1] pry(main)> user.errors => #<ActiveModel::Errors:0x00007fba4d3e0a80 @base=#<User id: nil, email: "", created_at: nil, updated_at: nil, nickname: "test">, @details={:email=>[{:error=>:blank}]}, @messages={:email=>["can't be blank"]}> [2] pry(main)> user.errors.full_messages => ["Email can't be blank"]
RSpec