首页 > 解决方案 > AASM + Rspec - 如何在测试中忽略/禁用/跳过转换回调?

问题描述

我有这样的课

class Job
  include AASM

  aasm do
    state :created, initial: true
    state :processing, :notifying, :finished, :error

    event :process do
      before do
        # do some undesired stuffs for test
      end
      transitions from: :created, to: :processing
    end

    event :notify do
      transitions from: :processing, to: :notifying
    end

    event :finish do
      before do
        # do more undesired stuffs for test
      end
      transitions from: [:processing, :notifying], to: :finished
    end

    event :error do
      transitions to: :error
    end
  end

  def notify?
    Date.today.saturday?
  end

  def run!
    process!
    notify! if notify?
    finish!
  rescue
    error!
  end
end

我想创建一个测试来验证是否run!按预期遵循工作流程,但是在我的转换中,我有一些我不想在此测试中触发的回调。

before do
  allow(job).to receive(:notify?).and_return(false)
  # do some magick to disable the callbacks
end

it do
  job.run!
  expect(job).to have_received(:process!)
  expect(job).to have_received(:finish!)
  expect(job).not_to have_received(:notify!)
  expect(job).not_to have_received(:error!)
end

是否有某种方法可以在 rspec 测试中禁用 AASM 回调,或者唯一的选择是模拟回调中的所有内容?

PS
我的实际课程比那些例子复杂得多。

标签: ruby-on-railsrubyrspecaasm

解决方案


您可以将回调逻辑包装在方法中并存根这些方法调用。例如。

    event :process do
      before do
        wrapped_method_one
        wrapped_method_two
      end
      transitions from: :created, to: :processing
    end

规格:

before { allow(job).to receive(:wrapped_method_one) } 
before { allow(job).to receive(:wrapped_method_two) } 

推荐阅读