Rails rspec如何捕获错误AASM :: InvalidTransition和ActiveModel :: ValidationError

时间:2019-06-05 11:15:37

标签: ruby-on-rails rspec rspec-rails

我想从两个错误(rescue和ActiveModel :: ValidationError)中测试我正在使用AASM::InvalidTransition的调用方法,并将其发送到rollbar。如果状态不存在,则应该显示验证错误。

def call
  all_to_expire.each do |offer|
    begin
      offer.expire!(actor: self)
    rescue AASM::InvalidTransition, ActiveModel::ValidationError => e
      Rollbar.error(e)
    end
  end
end

规格:

context 'when offer is invalid' do
    before do
      allow(BankOffers::CloseExpired).to receive(:new).and_return(invalid_expire)
      allow(invalid_expire).to receive(:call).and_raise(ActiveModel::ValidationError)
    end

    let(:invalid_expire) { instance_double(BankOffers::CloseExpired, call: nil) }

    it 'catch validation error' do
      expect do
        invalid_expire
      end.to raise_error(ActiveModel::ValidationError)
    end
  end
end

编辑:

所有规格已更新-我认为我必须使用instance_double并通过模拟所有服务引起错误,但最后我遇到了错误:

  expected ActiveModel::ValidationError but nothing was raised

1 个答案:

答案 0 :(得分:0)

您不应该模拟或存根该对象,因为那样您就不会进行任何测试,只需测试您设置了正确的模拟就可以了。

我会做类似的事情:

context 'when offer is invalid' do
  it 'catch validation error' do
    # this is the tricky part, you are not showing your model so I don't
    # know what's an invalid AASM transition, but you should set an status
    # that can't be transitioned to "expired" here
    invalid_offer = create(:bank_offer,
      inquiry_process: process_past_date_of_interest,
      status:  <<<something here>>>)

    expect(Rollbar).to receive(:error)
    invalid_offer.call
  end
end

您需要创建一个有效记录,但是状态不能转换为epired。然后,在Rollbar对象上添加期望,然后调用应该引发AASM异常的方法。确保您的对象有效,这样您就不会有其他错误隐藏正在测试的实际错误。

希望这会有所帮助。