title: Rspec testing delayed_job
body: <p>I have some complex, long-running delayed_job processes in my application. I am using Rspec to test individual methods and classes used in the processes, but I would also like to perform many of end-to-end background jobs, with different test data. </p>
  
  <p>I couldn't find anything on the delayed_job wiki on this, and this SO question looks interesting but I didn't really understand what is happening here.
  <a href="https://stackoverflow.com/questions/7030974/whats-the-best-way-to-test-delayed-job-chains-with-rspec">What&#39;s the best way to test delayed_job chains with rSpec?</a></p>
  
  <p>I can easily set up the test data with a factory, and then call the class that starts the background processing. I expect the tests to take a long time to complete.</p>
  
  <p>edited background code</p>
  
  <pre><code>class Singleplex
      def perform(batch_id,user)   
        batch = start_batch(batch_id,user)
          ... do lots of stuff ...
      end
      handle_asynchronously :perform, queue: :singleplex, :run_at =&gt; Proc.new { 1.second.from_now }
  </code></pre>
  
  <p><strong>spec/factories/batches.rb</strong></p>
  
  <pre><code>FactoryGirl.define do
    factory :batch do
      batch_type 'singleplex'
      name 'valid panel'
      status 'ready'
    end
  
    factory :batch_detail do
      chrom 7
      chrom_start 140435012
      chrom_end 140435012
      target_offset 150
      padding 4
      primer3_parameter_id 1
      snp_mask 't'
      status 'ready'
      batch
    end
  end
  </code></pre>
  
  <p>Then run the test like this</p>
  
  <pre><code>describe Batch do  
    it 'runs Singleplex for a valid panel' do
      batch = FactoryGirl.create(:batch)
      user = User.find(1)
      status =  Singleplex.new.perform(batch.id,user)
      expect(status.should == true)
    end
  end
  </code></pre>
  
  <p>I have two problems to solve:</p>
  
  <p>1) How to tell the test to wait until the delayed_job call is completed before validating the results ?</p>
  
  <p>2) To validate the results I will need to check values in multiple tables. What is the best way to do this in Rspec?</p>
  
  <p>EDIT</p>
  
  <p>I should add I get a delayed_job object, so of course the status check fails. The jobs take at least 10 minutes usually.</p>
  
  <pre><code>1) Batch runs Singleplex for a valid panel
       Failure/Error: expect(status.should == true)
         expected: true
              got: #&lt;Delayed::Backend::ActiveRecord::Job id: nil, priority: 0, attempts: 0, handler: "--- !ruby/object:Delayed::PerformableMethod\nobject:...", last_error: nil, run_at: nil, locked_at: nil, failed_at: nil, locked_by: nil, queue: nil, created_at: nil, updated_at: nil&gt; (using ==)
  </code></pre>