Skip to content

Instantly share code, notes, and snippets.

@jacegu
Last active December 19, 2015 10:19
Show Gist options
  • Save jacegu/5939799 to your computer and use it in GitHub Desktop.
Save jacegu/5939799 to your computer and use it in GitHub Desktop.
Playing around with sidekiq workers and dependency injection. You cannot create a new instance of the worker with dependencies injected and call `perform_async` on the instance. (This doesn't make much sense now that I've grasped how sidekiq works, but would have been nice). But you can achieve something similar using a factory to build the depe…
require_relative 'worker'
class Dispatcher
def self.dispatch_instance
Worker.new(STDOUT).perform_async('This is working')
end
def self.dispatch_class
Worker.perform_async('This is working')
end
end
begin
Dispatcher.dispatch_class
rescue => e
STDERR.puts "Dispatching async worker via class failed: #{e.message}"
end
begin
Dispatcher.dispatch_instance
rescue => e
STDERR.puts "Dispatching async worker via instance failed: #{e.message}"
end
module Factory
def self.outputer
STDOUT
end
end
require 'sidekiq'
require_relative 'factory'
class Worker
include Sidekiq::Worker
def initialize(outputer = Factory.outputer)
@outputer = outputer
end
def perform(output)
@outputer.puts('*'*80)
@outputer.puts(output)
@outputer.puts('*'*80)
end
end
require 'minitest/autorun'
require 'minitest/spec'
require 'minitest/mock'
require_relative 'lib/worker'
require 'sidekiq/testing'
describe Worker do
it 'uses the outputer to output the message' do
outputer = MiniTest::Mock.new
worker = Worker.new(outputer)
message = 'irrelevant message'
outputer.expect(:puts, nil, ['*'*80])
outputer.expect(:puts, nil, [message])
outputer.expect(:puts, nil, ['*'*80])
worker.perform(message)
outputer.verify
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment