Skip to content

Testing Your Worker

Matt Rothstein edited this page Apr 25, 2017 · 11 revisions

Testing

Example inspired by Sidekiq.fake testing mode

This example uses two helper modules for json (un-)marshalling and monkey patches them to give a interface similar to Sidekiq.fake.

spec/support/sneakers_helpers.rb

module Sneakers
  module Testing
    class << self
      def all
        messages_by_queue.values.flatten
      end
      def [](queue)
        messages_by_queue[queue]
      end

      def push(queue, message)
        messages_by_queue[queue] << message
      end

      def messages_by_queue
        @messages_by_queue ||= Hash.new { |hash, key| hash[key] = [] }
      end

      def clear_for(queue, klass)
        messages_by_queue[queue].clear
      end

      def clear_all
        messages_by_queue.clear
      end

    end
  end
end


module WorkerAdditions
  def publish(payload, opts)
    Sneakers::Testing.push(opts[:to_queue], payload)
  end
end


module QueuePublisher
  extend self
  def publish(payload, routing)
    Sneakers::Testing.push(routing[:to_queue], payload)
  end
end


RSpec.configure do |config|
  config.include WorkerAdditions
  config.include QueuePublisher
  config.include Sneakers::Testing

  config.before(:each) do
    Sneakers::Testing.clear_all
  end
end

worker_additions.rb (not technically part of mocking) include WorkerAdditions in actual workers after include Sneakers::Worker

module WorkerAdditions
  def work(message)
    data = JSON.parse(message, :symbolize_names => true)
    ActiveRecord::Base.connection_pool.with_connection do
      consume(data[:payload])
    end
    ack!
  end

  def publish(payload, opts)
    json = JSON.generate(payload: payload)
    super(json, opts)
  end
end

queue_publisher.rb

module QueuePublisher
  extend self
  def publish(payload, routing)
    json = JSON.generate(payload: payload)
    Sneakers.publish(json, routing)
  end
end