rspec-sidekiq icon indicating copy to clipboard operation
rspec-sidekiq copied to clipboard

Block syntax `enqueue_sidekiq_job` matcher

Open pirj opened this issue 4 years ago • 5 comments

There is a slight problem with the existing have_enqueued_sidekiq_job matcher, specifically that it's prone to the incidental state error, unlike rspec-rails's Active Job-oriented have_enqueued_job that is a block syntax matcher. E.g.:

class Model < ActiveRecord::Base
  after_save :schedule_job

  def foo!
    # I do nothing!
  end

  private

  def schedule_job
    AwesomeJob.perform_async('hello')
  end
end
RSpec.describe Model do
  describe '#foo!' do
    subject!(:model) { Model.create! }

    it 'schedules AwesomeJob' do
      model.foo!
      expect(AwesomeJob).to have_enqueued_sidekiq_job('hello')
    end
  end
end

In the above example, the job was scheduled. But it would be scheduled no matter if model.foo! was called or not.

I suggest adding a block-syntax enqueue_sidekiq_job matcher that would work similarly to rspec-rails's one:

RSpec.describe Model do
  describe '#foo!' do
    subject!(:model) { Model.create! }

    it 'schedules AwesomeJob' do
      expect { model.foo! }
        .to enqueue_sidekiq_job(AwesomeJob).with('hello')
    end
  end
end

I can handle adding it if you have no objections on the idea.

pirj avatar Dec 22 '20 10:12 pirj

Ping

pirj avatar Jan 11 '21 09:01 pirj

hey @pirj have you worked on this one? I like the idea and I'm curious if I can sneak the implementation :)

sineed avatar Feb 20 '21 10:02 sineed

I haven't yet, but since you support the idea, I'll tackle it. For the implementation, I think of something very similar to this.

pirj avatar Feb 20 '21 11:02 pirj

Yes, good to add negated matcher as well. It will be quite handy and readable to see something like:

expect { subject }
  .to have_enqueued_sidekiq_job(FooJob)
  .and have_enqueued_sidekiq_job(BarJob)
  .and avoid_enqueuing_sidekiq_job(BazJob)

sineed avatar Feb 20 '21 12:02 sineed

Released as https://github.com/pirj/rspec-enqueue_sidekiq_job https://rubygems.org/gems/rspec-enqueue_sidekiq_job

I've closed the PR. Please feel free to close the ticket as well.

pirj avatar Mar 21 '21 15:03 pirj

I'd like this in rspec-sidekiq and I've added it as a goal for v4. If you're still interested @pirj (I know it's been several years), feel free to re-open a PR. Otherwise I'll try and add a block syntax version using the same style expect { }.to enqueue_sidekiq_job(...)

wspurgin avatar Aug 01 '23 13:08 wspurgin

I ended up creating https://github.com/pirj/rspec-enqueue_sidekiq_job Since we don’t use Sidekiq directly in my current project, I’m not so interested in actively maintaining the repo further. I’ll be happy if you take it over, borrow its code, or just include the gem as a runtime dependency, whatever you feel is right.

And thanks for the gem!

pirj avatar Aug 01 '23 18:08 pirj

Thanks @pirj 👍 Appreciate it.

wspurgin avatar Aug 02 '23 12:08 wspurgin