awsm sid
awsm sid

Reputation: 595

How to write rspec for rails jobs

Hi i am working with a RoR project with ruby-2.5.0 and rails 5. I am using AWS SQS. I have created a job as follows:-

class ReceiptsProcessingJob < ActiveJob::Base
  queue_as 'abc'

  def perform(receipt_id)
    StoreParserInteractor.process_reciept(receipt_id)
  end
end

Now i want to write unit test for it. I tried like:-

# frozen_string_literal: true

require 'rails_helper'

describe ReceiptsProcessingJob do

  describe "#perform_later" do
    it "scan a receipt" do
      ActiveJob::Base.queue_adapter = :test
      expect {
        ReceiptsProcessingJob.perform_later(1)
      }.to have_enqueued_job
    end
  end
end

But it doesnot cover StoreParserInteractor.process_reciept(receipt_id). Please help how can i cover this. Thanks in advance.

Upvotes: 3

Views: 5305

Answers (2)

kitschmaster
kitschmaster

Reputation: 1299

The example is testing the job class. You need to write a spec for StoreParserInteractor and test the method process_reciept.

Something along the lines of (pseudo code):

describe StoreParserInteractor do
  describe "#process_receipt" do
    it "does that" do
      result = StoreParserInteractor.process_receipt(your_data_here)
      expect(result to be something)...
    end
  end
end

But, the Rails guide suggests this kind of test:

assert_enqueued_with(job: ReceiptsProcessingJob) do
  StoreParserInteractor.process_reciept(receipt_id)
end

Maybe this increases code coverage as well.

Upvotes: 1

Luiz E.
Luiz E.

Reputation: 7249

In my opinion, you shouldn't actually test the ActiveJob itself, but the logic behind it.

You should write a test for StoreParserInteractor#process_reciept. Think of ActiveJob as an "external framework" and it is not your responsibility to test the internals of it (e.g. if the job was enqueued or not).

As kitschmaster said, don't test ActiveJob classes, in short

Upvotes: 1

Related Questions