DEV Community

Dmitry Daw
Dmitry Daw

Posted on

4

Trick to cleaner use Sidekiq::Testing.inline! in tests

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

With this approach, you can better control when Sidekiq jobs are processed during testing, leading to cleaner tests.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more