ruby 如何在RSpec测试中引发异常

hjqgdpho  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(97)

我被一个测试场景卡住了。
我有一个控制器方法:

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

n3ipq98p

n3ipq98p1#

像这样,比如说

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

字符串

cigdeys3

cigdeys32#

我会这样做:

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

字符串
请注意,我对测试设置中的stubbing方法(在本例中我更喜欢allow)和实际期望值(expect)进行了区分。

相关问题