LoginSignup
45
25

More than 3 years have passed since last update.

Rspecでモデルのvalidateをテストするときの注意

Last updated at Posted at 2017-10-10

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
45
25
3

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
45
25