By default, Sidekiq jobs don't run in tests. But sometimes, e.g. in e2e tests, you'd want them to run. Sidekiq provides a method Sidekiq::Testing.inline!
that enables job processing.
If you run this method once, it enables job processing in all tests; if you run it with a block, it processes jobs only within that block. But it's not very clean to have blocks everywhere in your tests. So there's a trick to isolate Sidekiq::Testing.inline!
within the scope of your full test or specific contexts.
You can utilize RSpec's configuration options to control when Sidekiq::Testing.inline!
is invoked. You can set it up to run based on the presence of specific metadata in your tests, like so:
# spec/spec_helper.rb
RSpec.configure do |config|
...
config.around do |example|
if example.metadata[:sidekiq_inline] == true
Sidekiq::Testing.inline! { example.run }
else
example.run
end
end
...
end
With this configuration, Sidekiq::Testing.inline!
will only run when the :sidekiq_inline
metadata is present and set to true in a test. This can be done as follows:
context 'my context', :sidekiq_inline do
# your tests go here
end
describe 'my describe', :sidekiq_inline do
# your tests go here
end
it 'my test', :sidekiq_inline do
# your test goes here
end
With this approach, you can better control when Sidekiq jobs are processed during testing, leading to cleaner tests.
Top comments (0)