如何在 RSpec 测试中引发异常

How to raise an exception in an RSpec test

我卡在测试场景中了。

我有一个控制器方法:

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

比如这样

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)。