如何使用 Rspec 测试是否调用了 Rails 6 的 `discard_on`?

问题描述 投票:0回答:1

我有一份工作,应该放弃一个特定的错误:

class SomeJob < ApplicationJob
discard_on(Errno::ENOENT) do |job, error|
    ...do things...
   end

   def perform(**args)
     ...do things...
   end
end

我已经尝试过,基于如何使用rspec正确测试ActiveJob的retry_on方法?来模拟测试它:

context '#discard_on' do
      it 'should discard on Errno::ENOENT error' do
        expect_any_instance_of(described_class).to receive(:perform).and_raise(Errno::ENOENT.new)
        expect(SomeJob).to have_received(:discard_on)

        UploadJob.perform_now(**args)
      end
    end

但我不断收到以下错误:

 #<SomeJob (class)> expected to have received discard_on, but that object is not a spy or method has not been stubbed.

如果我这样尝试:

expect_any_instance_of(SomeJob).to receive(:perform).and_raise(Errno::ENOENT)
expect_any_instance_of(described_class).to receive(:discard_on)

SomeJob.perform_now(**args)

失败并出现以下错误:

SomeJob does not implement #discard_on
ruby-on-rails rspec rails-activejob
1个回答
0
投票

这是我发现的最好的方法:

      # mock logger
      let(:log_output) { StringIO.new }
      let(:logger) { Logger.new(log_output) }

      around do |example|
        original_logger = ActiveJob::Base.logger
        ActiveJob::Base.logger = logger

        example.run

        ActiveJob::Base.logger = original_logger
      end

      it "discards the message if XYZ" do
        MyJob.perform_now("123.xyz")

        # check log output
        expect(log_output.string).to include "Discard"
      end
© www.soinside.com 2019 - 2024. All rights reserved.