如何在RSpec测试中引发exception

我陷入了测试场景。

我有一个控制器方法:

def update @object = Object.find params[:id] # some other stuff @object.save rescue ActiveRecord::StaleObjectError # woo other stuff end 

第一部分我测试:

 context '#update' let(:object) { double } it 'nothing fails' do # some other stuff expect(Object).to receive(:find).with('5').and_return(object) expect(object).to receive(:save).and_return(true) xhr :put, :update, id:5 expect(response).to be_success expect(assigns(:object)).to eq(object) end end 

现在我想测试ActiveRecord::StaleObjectErrorexception。 我想把它存根,但我没有找到任何解决方法如何做到这一点。

所以我的问题是,如何在RSpec测试中引发ActiveRecord::StaleObjectError

例如,像这样

 expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError) 

我会做这样的事情:

 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 end end 

请注意,我在测试设置中的存根方法(在这种情况下我更喜欢allow )和实际期望( expect )之间有所不同。