Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing tests for a sidekiq worker

Tags:

I am using the rspec-sidekiq gem (https://github.com/philostler/rspec-sidekiq) to help test a worker I am writing, but for some reason my test keeps failing.

Here is my Test:

require 'spec_helper'  describe CommunicationWorker do   it { should be_retryable false }    it "enqueues a communication worker" do     subject.perform("[email protected]", "[email protected]", [1,2,3])     expect(CommunicationWorker).to have_enqueued_jobs(1)   end end 

Here is the error:

 1) CommunicationWorker enqueues a communication worker      Failure/Error: expect(CommunicationWorker).to have_enqueued_jobs(1)        expected CommunicationWorker to have 1 enqueued job but got 0      # ./spec/workers/communication_worker_spec.rb:9:in `block (2 levels) in <top (required)>' 

I based my low-level test off of their example on their wiki, but it's not working for me... any reason why this wouldn't work?

like image 735
dennismonsewicz Avatar asked Sep 12 '13 02:09

dennismonsewicz


People also ask

How do I test my Sidekiq workers?

To test your Sidekiq Worker jobs array, run WorkerNameHere.jobs in terminal and see if it contains your job with your jid. If it does, then it was enqueued in Sidekiq to be run as a job.

How do I test Sidekiq locally?

On the browser, goto ==> http://localhost:{port}/sidekiq/recurring-jobs . where {port} is the port your application is running in. You will see the list of scheduled jobs for your application and some other details about it. Show activity on this post.


2 Answers

There are two things to test for here, the asynchronous enqueuing of the job in the queue and the execution of the job.

You can test the execution of the job by instantiating the job class and calling perform().

You can test the enqueuing of the job by calling perform_async() on the job class.

To test the expectation in your test, you should be doing:

 it "enqueues a communication worker" do     CommunicationWorker.perform_async("[email protected]", "[email protected]", [1,2,3])     expect(CommunicationWorker).to have(1).jobs   end 

However, this is really just testing the Sidekiq framework and not a useful test. I would recommend writing tests for the internal behavior of the job itself:

 it "enqueues a communication worker" do     Widget.expects(:do_work).with(:some_value)     Mailer.expects(:deliver)      CommunicationWorker.new.perform("[email protected]", "[email protected]", [1,2,3])   end 
like image 100
Winfield Avatar answered Oct 19 '22 10:10

Winfield


What is the testing method? Try wrapping your existing test with Sidekiq::Testing.fake! do <your code> end. This will ensure the a fake queue is used. If sidekiq's testing methods is 'inline', the worker will be executed right away (and thus your queue will be 0 length).

Check out: https://github.com/mperham/sidekiq/wiki/Testing for more info.

like image 31
cgat Avatar answered Oct 19 '22 10:10

cgat