1

如何在RSPEC中测试或存根Sidekiq::Batch

请参阅下面的代码中出现错误

rails_helper

  require 'spec_helper'
  require File.expand_path('../../config/environment', __FILE__)
  # Prevent database truncation if the environment is production
  abort("The Rails environment is running in production mode!") if Rails.env.production?
  require 'rspec/rails'
  require 'sidekiq/testing'
  Sidekiq::Testing.fake!

待测试的工人...

class TestWorker
    def perform(id)
        batch = Sidekiq::Batch.new
        batch.description = "Sample"
        batch.on(:complete, TestWorker, 'id' => 123, 'last_checked' => Time.now)
        # =>  *** NoMethodError Exception: undefined method `on' for #<Batch:0x007fd8b728a1d0>

        batch.jobs do # => NoMethodError: undefined method `jobs' for #<Batch:0x007f936c9ebf68>
          Sidekiq::Client.push({
             'class' => TestWorker,
             'queue' => q,
             'args'  => [id, batch.bid, 1, Time.now]
          })
        end
    end
end

class TestWorkerCallbacks
  def complete(status, options)
    #simple record update here
  end
end

规范/工人/test_worker_spec.rb

require 'rails_helper'

RSpec.describe TestWorker, type: :worker do
  context "Sidekiq Worker" do
    it "should respond to #perform" do
      expect(TestWorker.new).to respond_to(:perform)
    end

    describe "perform" do
      before do
        Sidekiq::Worker.clear_all
      end

      it "updates order records" do
        expect(TestWorker.jobs.size).to eq(0)
        TestWorker.perform_async(123)
        TestWorker.drain
        expect(TestWorker.jobs.size).to eq(1)
      end
    end
  end

end
4

0 回答 0