
Yesterday I came accross a tricky useage of raise_error matcher in rspec, first I try to use the one line syntax is_expected.to
it { is_expected.to raise_error(SomeError) }
but I got an eror which stops the test before the test is finished.
It is confusing in the first time, because is_expected.to is shortcut for expect(subject).
Then I found this excellent explanation in Github isses.
So expect(subject) is not a block, subject is executed instantly, so rspec will stop before evaluating raise_error matcher.
In order to make it work, we can make subject itself a block
subject { -> { raise SomeError } }
it { is_expected.to raise_error(SomeError) }
But this syntax is creepy, instead it’s better to use
subject { raise SomeError }
expect { subject }.to raise_error(SomeError)




近期评论