3

我有一个 Resque 工作,我正在尝试使用 rspec 进行测试。这份工作看起来像:

class ImporterJob

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

我正在使用 Resque 状态,所以我使用 create 方法来创建作业,如下所示:

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

如果我尝试在 rspec 测试中以相同的方式创建作业,则选项似乎无法完成作业。如,当我在 之后插入 binding.pry 时user = options['user'],选项哈希为空。

我的 rspec 测试如下所示:

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
4

1 回答 1

6

对于单元测试,不建议在不同的线程/进程上运行您正在测试的代码(这就是 Requeue 正在做的事情)。相反,您应该通过直接运行来模拟这种情况。幸运的是,Resque有一个功能叫做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

因此,您的测试应如下所示:

it 'validates and imports csv data' do
  Resque.inline do
    ImporterJob.create(import_options)
  end
end
于 2014-03-05T16:17:59.127 回答