title: Testing a service object job with rspec
body: <p>I have the following job:</p>
  
  <pre><code>class Test::MooJob &lt; ApplicationJob
    queue_as :onboarding
  
    def perform
       avariable = Test::AragornService.build("a").call
       if avariable.status == true
          puts "job succeeded"
       end
    end
  end
  </code></pre>
  
  <p>and the service looks like this: </p>
  
  <pre><code>module Test
    class AragornService
  
      def self.build(x)
        self.new(x)
      end
  
      def initialize(x)
        @x = x
      end
  
      def call
        10.times do
          Rails.logger.info @x
        end
  
        return ServiceResult.new :status =&gt; true, :message =&gt; "Service Complete", :data =&gt; @x
  
      rescue =&gt; e
        Bugsnag.notify(e, :context =&gt; 'service')
        return ServiceResult.new :status =&gt; false, :message =&gt; "Error occurred - #{e.message}"
      end
  
    end
  end
  </code></pre>
  
  <p>I am trying to test it with the following spec:</p>
  
  <pre><code># bundle exec rspec spec/jobs/test/moo_job_spec.rb
  require "rails_helper"
  
  describe Test::MooJob do
    subject(:job) { described_class.perform_later }
    subject(:job_now) { described_class.perform_now }
  
    let(:key) { "a" }
  
    it 'queues the job' do
      ActiveJob::Base.queue_adapter = :test
      expect { job }.to have_enqueued_job(described_class)
        .on_queue("onboarding")
    end
  
    it 'calls the aragorn service once' do
      allow(Test::AragornService.new(key)).to receive(:call).and_return(ServiceResult.new(:status =&gt; true))
      expect_any_instance_of(Test::AragornService).to receive(:call).exactly(1).times
      job_now
    end
  
  end
  </code></pre>
  
  <p>Why is it that avariable value keeps returning nil
  I get the following error "undefined method `status' for nil:NilClass"</p>
  
  <p>however, when I return a simple boolean,</p>
  
  <p>allow(Test::AragornService.new(key)).to receive(:call).and_return(true)</p>
  
  <p>It sets avariable value to true </p>
  
  <p>here's the ServiceResult class:</p>
  
  <pre><code>class ServiceResult
    attr_reader :status, :message, :data, :errors
  
    def initialize(status:, message: nil, data: nil, errors: [])
      @status = status
      @message = message
      @data = data
      @errors = errors
    end
  
    def success?
      status == true
    end
  
    def failure?
      !success?
    end
  
    def has_data?
      data.present?
    end
  
    def has_errors?
      errors.present? &amp;&amp; errors.length &gt; 0
    end
  
    def to_s
      "#{success? ? 'Success!' : 'Failure!'} - #{message} - #{data}"
    end
  
  end
  </code></pre>