LoginSignup
0
0

More than 1 year has passed since last update.

単体テストコードエラー解消 Failure/Error: expect(@user.errors.full_messages).to include("First name can't be blank")

Posted at

◉単体テストコード発生 Failure/Error: expect(@user.errors.full_messages).to include("First name can't be blank")

◯furimaアプリ実装中に単体テストコードを実装

エラーメッセージが発生したのでその時の対処と共にアウトプット

spec/models/user_spec.rb
require 'rails_helper'

RSpec.describe User, type: :model do
  describe '#create' do
    before do
      @user = FactoryBot.build(:user)
    end

    it 'passwordとpassword_confirmationが5文字以下では登録できない' do
      @user.password = '00000'
      @user.password_confirmation = '00000'
      @user.valid?
      expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
    end
    it 'nicknameが空では登録できない' do
      @user.nickname = ''
      @user.valid?
      expect(@user.errors.full_messages).to include ("Nickname can't be blank")
    end
    it 'emailが空では登録できない' do
      @user.email = ''
      @user.valid?
      expect(@user.errors.full_messages).to include("Email can't be blank")
    end
    it 'emailは@が含まれていなければ登録できない' do
      @user.email = 'sample.com'
      @user.valid?
      expect(@user.errors.full_messages).to include("Email is invalid")
    end
    it 'passwordが空では登録できない' do
      @user.password = ''
      @user.valid?
      expect(@user.errors.full_messages).to include("Password can't be blank")
    end
    it 'first_nameが空では登録できない' do
      @user.first_name = ''
      @user.valid?
      expect(@user.errors.full_messages).to include("First_name can't be blank")
      # ここでエラーが発生した
    end

エラーメッセージは↓

1) User#create first_nameが空では登録できない
     Failure/Error: expect(@user.errors.full_messages).to include("First name can't be blank")
       expected [] to include "First name can't be blank"
     # ./spec/models/user_spec.rb:38:in `block (3 levels) in <top (required)>'

よく見ていくと
to include後の("First name can't be blank")とエラーが記載されている。

もしかしたら、_がいらないのか?と仮定し削除して再度bundle exec rspec spec/models/user_spec.rb 実行。

User
  #create
    passwordとpassword_confirmationが5文字以下では登録できない
    nicknameが空では登録できない
    emailが空では登録できない
    emailは@が含まれていなければ登録できない
    passwordが空では登録できない
    first_nameが空では登録できない
    last_nameが空では登録できない
    first_name_kanaが空では登録できない
    last_name_kanaが空では登録できない
    birthdayが空では登録できない
    passwordが存在してもpassword_confirmationが空では登録できない
    重複したemailが存在する場合登録できない
    passwordが5文字以下では登録できない

Finished in 0.1892 seconds (files took 1.01 seconds to load)
13 examples, 0 failures

なんとか解消!!

_の部分は忘れがちなので注意して覚えておこう!

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