valid?を忘れずに
newでvalidateに引っかかるインスタンスを作成しても、valid?を行わなければerrors.messagesは格納されていない。
なので必ずnewでインスタンスを作った後expectの前にvalid?を行うこと。
Hoge.rb
#モデル
class Patient < ApplicationRecord
#validate
validates :name, presence: true #名前を必須
end
hoge_spec.rb
require 'rails_helper'
# 下はho.errors.messages[:name]の値が空でテストが失敗する。
RSpec.describe Patient, type: :model do
it 'is invalid without a name' do
ho = Hoge.new()
expect(ho.errors.messages[:name]).to include('Can not be blank')
end
end
# valid?を事前に行うと、errors.messagesにエラーの値が格納される。(テスト成功)
RSpec.describe Patient, type: :model do
it 'is invalid without a name' do
ho = Hoge.new()
ho.valid?
expect(ho.errors.messages[:name]).to include('Can not be blank')
end
end