3

I have a Resque job that I am trying to test using rspec. The job looks something like:

class ImporterJob

def perform
 job_key = options['test_key']
 user = options['user']
end

I am using Resque status so I am using the create method to create the job like so:

ImporterJob.create({key:'test_key',user: 2})

If I try to create a job the same way in an rspec test, the options appear to not be making it to the job. As in, when I insert a binding.pry after user = options['user'], the options hash is empty.

My rspec test looks like this:

describe ImporterJob do
  context 'create' do

    let(:import_options) {
      {
        'import_key' => 'test_key',
        'user' => 1,
        'model' => 'Test',
        'another_flag' => nil
      }
    }

    before(:all) do
      Resque.redis.set('test_key',csv_file_location('data.csv'))
    end

    it 'validates and imports csv data' do
      ImporterJob.create(import_options)
    end
  end
end
Jackson
  • 6,391
  • 6
  • 32
  • 43
  • 1
    What happens if you pass a `Hash` with `symbols` instead of strings? `:import_key => 'test_key'` – Uri Agassi Mar 05 '14 at 12:35
  • It appears the same issue if I pass a hash. – Jackson Mar 05 '14 at 15:26
  • Yep, I meant symbols. Sorry about that. I actually realized the issue but not sure how to fix it still. The jobs are being queued up but there are no workers to run them. Is there a way in tests to start a worker to run a job? – Jackson Mar 05 '14 at 16:07

1 Answers1

6

For unit-testing it is not advisable to run the code you are testing on a different thread/process (which is what Requeue is doing). Instead you should simulate the situation by running it directly. Fortunately, Resque has a feature called inline:

  # If 'inline' is true Resque will call #perform method inline
  # without queuing it into Redis and without any Resque callbacks.
  # If 'inline' is false Resque jobs will be put in queue regularly.
  # @return [Boolean]
  attr_writer :inline

  # If block is supplied, this is an alias for #inline_block
  # Otherwise it's an alias for #inline?
  def inline(&block)
    block ? inline_block(&block) : inline?
  end

So, your test should look like this:

it 'validates and imports csv data' do
  Resque.inline do
    ImporterJob.create(import_options)
  end
end
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
  • I tried using Resque.inline, and now the job isn't even being queued up. Not sure if I am missing something. – Jackson Mar 05 '14 at 16:29
  • The job is not supposed to be queued up, it is supposed to run, well... inline. You can see the implementation here - https://github.com/resque/resque/blob/master/lib/resque/job.rb – Uri Agassi Mar 05 '14 at 16:35