如何在RSpec测试中引发异常

时间:2015-09-02 13:20:42

标签: ruby-on-rails ruby rspec rspec3

我坚持测试场景。

我有一个控制器方法:

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异常。我想留下它,但我没有找到任何解决方法如何做到这一点。

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

2 个答案:

答案 0 :(得分:11)

像这样,例如

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

答案 1 :(得分:2)

我会做这样的事情:

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)之间存在差异。