How to raise an exception in an RSpec test
Like this, for example
expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)
I would do something like this:
describe '#update' do let(:object) { double } before do allow(Object).to receive(:find).with('5').and_return(object) xhr(:put, :update, id: 5) end context 'when `save` is successful' do before do allow(object).to receive(:save).and_return(true) end it 'returns the object' do expect(response).to be_success expect(assigns(:object)).to eq(object) end end context 'when `save` raises a `StaleObjectError`' do before do allow(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError) end it 'is not successful' do expect(response).to_not be_success end endend
Please note that I make a difference between stubing methods in the test setup (I prefer allow
in this case) and the actual expectation (expect
).