17

A large part of my application relies on background jobs to process user's websites, so I need to write some tests to cover these.

First question is how to test code that's in a Sidekiq worker class, for example app/workers/some_worker.rb

class SomeWorker
  include Sidekiq::Worker

  def perform(model_id)
    ...
  end
end

Secondly, how do I stub code such as the following so I don't need to actually run workers and slow down my tests?

response = HTTParty.get("http://users-site.com", timeout: 30)
mind.blank
  • 4,820
  • 3
  • 22
  • 49

3 Answers3

13

Read the Testing page in the Sidekiq wiki.

Joe Lencioni
  • 10,231
  • 18
  • 55
  • 66
Mike Perham
  • 21,300
  • 6
  • 59
  • 61
  • Woops I missed that, I see I can use `work = HardWorker.new; work.perform(1, 2)` to run the code. Still not sure how to go about faking external sites for the tests though. – mind.blank Mar 30 '13 at 16:44
  • 1
    [Aforementioned Sidekiq wiki page on testing](https://github.com/mperham/sidekiq/wiki/Testing). – Sarah Vessels Oct 29 '13 at 15:00
  • @mind.blank have a look at [VCR](https://github.com/vcr/vcr) for stubbing your API calls – Ruy Diaz Mar 03 '20 at 00:08
10

Take a look at the rspec-sidekiq gem I've authored to do exactly this (testing of Sidekiq workers).

Phil Ostler
  • 429
  • 3
  • 14
2

Sidekiq provides a few options for testing your workers

https://github.com/mperham/sidekiq/wiki/Testing

For me it worked after I add these lines at the top of a spec-file

require 'sidekiq/testing'
Sidekiq::Testing.inline!
Unkas
  • 3,522
  • 2
  • 19
  • 23