RSpec define inline class to test modules

kinopyo avatar

kinopyo

It can be useful to define an inline disposable class in the spec so you can test a module/concern or a middleware cleanly and separately.

let(:plain_worker) do
  Class.new do
    include Sidekiq::Worker
    include SomeAwesomeMagic

    def perform
      "..."
    end
  end
end

before do
  stub_const("PlainWorker", plain_worker)
end

it "works" do
  Sidekiq::Testing.inline! do
    PlainWorker.perform_async # PlainWorker is the one we defined above
  end
end

We define a class with Class.new and then use RSpec stub_const to pair the class object to the constant you want.
stub_const will remove the stubbed constant after the life cycle of the spec, so it won't be exposed to the outer scope. ✅

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.