Last active
September 14, 2022 08:48
-
-
Save quanon/c147c28c5ff0b401579ec9e4e1706db0 to your computer and use it in GitHub Desktop.
RSpec での例外処理について
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hoge | |
class InvalidBlockError < StandardError; end | |
attr_accessor :result, :error | |
# 渡されたブロックを実行して、結果をプロパティに格納するインスタンスメソッド。 | |
def call | |
yield | |
self.result = :success | |
rescue => e | |
self.result = :failure | |
self.error = e | |
raise(InvalidBlockError) | |
end | |
end | |
describe Hoge do | |
describe '.call' do | |
let(:hoge) { described_class.new } | |
context '正常なブロックを渡した場合' do | |
subject { hoge.call { 1 * 0 } } | |
it '呼び出し後の hoge のプロパティが正しいこと' do | |
subject | |
expect(hoge).to have_attributes(result: :success, error: nil) | |
end | |
end | |
context '例外が発生するブロックを渡した場合' do | |
# ここで rescue はしたくない。 | |
# 例外をそのまま発生させることを期待しているテストケースもあるかもしれないし、それがそもそも本来の挙動なので。 | |
# 複数のテストケースで参照されるような before や subject などで rescue するのは避けたいです。 | |
# | |
# subject { hoge.call { 1 / 0 } rescue nil } | |
subject { hoge.call { 1 / 0 } } | |
it '呼び出し後の hoge のプロパティが正しいこと (非推奨)' do | |
# これでも実現できるけど、 | |
# 例外を抑制するために expect を使うのは本来の使い方ではないので避けたい。 | |
expect { subject }.to raise_error(described_class::InvalidBlockError) | |
expect(hoge.result).to eq(:failure) | |
expect(hoge.error).to be_a(ZeroDivisionError) | |
end | |
# テストケースをまとめるのも避けたい。 | |
it 'InvalidBlockError が発生し、呼び出し後の hoge のプロパティが正しいこと (非推奨)' do | |
expect { subject }.to raise_error(described_class::InvalidBlockError) | |
expect(hoge.result).to eq(:failure) | |
expect(hoge.error).to be_a(ZeroDivisionError) | |
end | |
# やっぱりこれが一番いいかな。 | |
it '呼び出し後の hoge のプロパティが正しいこと' do | |
subject rescue described_class::InvalidBlockError | |
expect(hoge.result).to eq(:failure) | |
expect(hoge.error).to be_a(ZeroDivisionError) | |
end | |
it 'InvalidBlockError が発生すること' do | |
expect { subject }.to raise_error(described_class::InvalidBlockError) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment