【问题标题】:Rails rspec how to catch error AASM::InvalidTransition and ActiveModel::ValidationErrorRails rspec 如何捕获错误 AASM::InvalidTransition 和 ActiveModel::ValidationError
【发布时间】:2019-06-05 11:15:37
【问题描述】:

我想从两个错误中测试我使用rescue 的调用方法 - AASM::InvalidTransition 和 ActiveModel::ValidationError 并将其发送到 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

【问题讨论】:

  • 您确定您的设置实际上应该引发您想要的异常吗?使用 byebug,在调用 .expire! 之前停止 call 方法内的执行并检查对象,也许您没有代码引发异常所需的状态。
  • 好的@arieljuod你是对的,我没有一个可以失败的例子。我的问题是如何获得一个将传递给调用方法的方法,其中包含无效字段和上升验证错误。是的,我肯定想要这个rescue
  • 就我所见,我必须使用 mock (?) 来伪造实现并强制出错,但我不知道该怎么做......

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


【解决方案1】:

你不应该模拟或存根这个对象,因为那样你就不会测试任何东西,你只会测试你设置了正确的模拟,这是无用的。

我会这样做:

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 异常的方法。确保您的对象是有效的,这样您就没有隐藏您正在测试的实际错误的其他错误。

希望这会有所帮助。

【讨论】:

  • 好的,我发现了不同的方法来获得无效的价值,所以当你从不同的银行传入顾问时。像create(:bank_offer, etc, etc, bank_advisor: advisor (which is another let with proper value) 这样的东西。这样,银行顾问就不是来自同一家银行。所以现在在控制台我有错误是:ActiveRecord::RecordInvalid: Validation failed: Bank advisor is not from the same bank 仍然没有,零个绿点。不过我觉得你的思路不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多