LoginSignup
1
0

More than 3 years have passed since last update.

rspecで例外が起きたことを確認する

Posted at

この記事で書くこと :pen_ballpoint:

以下のような処理でのensureの処理が走ったかどうかを確認する方法

class Cat < ApplicationRecord
  validates :todays_foods, presence: true

  def sing!
    sing_a_song!
  ensure
    say_hello
  end

  def say_hello
    'にゃーん'
  end

  def sing_a_song!
    if todays_foods.empty?
      raise お腹が空いてたらエラー
      return
    end
    'にゃにゃにゃーん!'
  end
end

テストの中身

  describe '#sing!' do
     context 'with exception error,' do
       let!(:cat) do
         cat = build(:cat, name: 'お腹すいた猫', todays_foods: 0)
         cat.save(validate: false) # validatesを無効にして作成。
         cat
       end
       it 'say にゃーん.' do
         expect do
           cat.sing!
         end.to raise_error(ActiveRecord::RecordInvalid).and(eq('にゃーん'))
       end
     end
  end
1
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
1
0