测试回滚和异常

时间:2018-09-03 12:58:41

标签: ruby-on-rails activerecord ruby-on-rails-5

我有以下(伪)代码:

def upgrade_to_ultimate
    active_order = @user.single_active_order
    UpgradeService.upgrade_to_ultimate(active_order)
    render 'accounts/show'
  rescue BTR::UpgradeService::UpgradePaymentFailed
    error_code(code: 'ord_010')
  end

和服务:

order.transaction do
   # close current order 
   # remove premium time from current order
   # create new_order
   response = charge_new_order
   raise BTR::UpgradeService::UpgradePaymentFailed if response.refusal_reason.present?
end

基本上,在升级过程中,我们从当前订单中删除了所有保费时间并创建了一个新订单,但是如果我们尝试对新订单收费,而我失败了,则必须回滚,这样用户才不会失去任何保费时间一切都保持不变。

这按预期工作,但我可以找到一种简单的测试方法。

我尝试过:

  context 'when the upgrade payment fails' do
      let(:fake_cse) { create(:adyen_cse_response, :failed) }

      it 'raises an error' do
        allow_any_instance_of(ChargeOrderService).to receive(:charge_order).and_return fake_cse
        expect { subject }.to raise_error(UpgradeService::UpgradePaymentFailed)
      end

      it 'does not change premium time' do
        allow_any_instance_of(ChargeOrderService).to receive(:charge_order).and_return fake_cse
        expect { subject }.not_to change { premium_order.reload.paid_premium_until }
      end
    end

和第一次测试通过(引发了错误),但是我不能测试第二种情况(it does not change premium time),因为当然会引发错误。

我尝试加注ActiveRecord::Rollback,而发生的事情却恰恰相反:我可以测试保费时间保持不变,但实际上没有例外。

是否可以提出例外情况测试加班时间?

0 个答案:

没有答案