この記事で書くこと
以下のような処理での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