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 Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay