我卡在了一个测试场景中。
我有一个 Controller 方法:
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::StaleObjectError
异常。我想 stub ,但我没有找到任何解决方案。
所以我的问题是,如何在 RSpec 测试中引发 ActiveRecord::StaleObjectError
?
最佳答案
比如这样
expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)
关于ruby-on-rails - 如何在 RSpec 测试中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32354356/