首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用RSpec 3测试sidekiq perform_in

使用RSpec 3测试sidekiq perform_in
EN

Stack Overflow用户
提问于 2014-08-11 22:14:25
回答 4查看 8.3K关注 0票数 5

RSpec 3和sidekiq 3.2.1。我已经正确地设置了sidekiq和rspec-sidekiq。

假设我有一个名为WeatherJob的工作程序,它将把天气状态从sunny更改为rainy

代码语言:javascript
复制
class WeatherJob
  include Sidekiq::Worker

  def perform record_id
    weather = Weather.find record_id

    weather.update status: 'rainy'
  end
end

我像这样使用这个工人:

WeatherJob.perform_in 15.minutes, weather.id

在规范中,我使用Timecop模拟时间:

代码语言:javascript
复制
require 'rails_helper'

describe WeatherJob do
  let(:weather) { create :weather, status: 'sunny' }
  let(:now)     { Time.current }

  it 'enqueue a job' do
    expect {
      WeatherJob.perform_async weather.id
    }.to change(WeatherJob.jobs, :size).by 1
  end

  context '15 mins later' do
    before do
      Timecop.freeze(now) do
        Weather.perform_in 15.minutes, weather.id
      end
    end

    it 'update to rainy' do
      Timecop.freeze(now + 16.minutes) do
        expect(weather.status).to eq 'rainy'
      end
    end
  end
end

我可以看到Weather.jobs数组中有作业。时间准确地说是16分钟后。但是它没有执行作业?有什么建议吗?谢谢!

EN

回答 4

Stack Overflow用户

发布于 2014-08-12 04:47:47

Sidekiq有三种测试模式:禁用、伪造和内联。默认值是fake,它只是将所有作业推入作业数组中,这就是您所看到的行为。内联模式会立即运行作业,而不是将其排入队列。

要强制Sidekiq在测试期间以内联方式运行作业,请将测试代码包装在Sidekiq::Testing.inline!块中:

代码语言:javascript
复制
before do
  Sidekiq::Testing.inline! do
    Timecop.freeze(now) do
      Weather.perform_in 15.minutes, weather.id
    end
  end
end

有关测试Sidekiq的更多信息,请参阅official Testing wiki page

票数 5
EN

Stack Overflow用户

发布于 2017-02-13 21:24:47

分两步完成。首先测试作业是否已调度,然后在没有时间延迟的情况下执行作业。下面是一个例子

代码语言:javascript
复制
it "finishes auction  (async)" do
  auction = FactoryGirl.create(:auction)
  auction.publish!

  expect(AuctionFinishWorker).to have_enqueued_sidekiq_job(auction.id).at(auction.finishes_at)
end

it "finishes auction  (sync)" do
  auction = FactoryGirl.create(:auction)
  auction.publish!

  Sidekiq::Testing.inline! do
    AuctionFinishWorker.perform_async(auction.id)
  end

  auction.reload
  expect(auction).to be_finished
end

have_enqueued_sidekiq_job方法来自于rspec-sidekiq gem。他们在develop分支机构进行了积极的开发。一定要像这样把它包括进去

代码语言:javascript
复制
  gem 'rspec-sidekiq', github: "philostler/rspec-sidekiq", branch: "develop"
票数 3
EN

Stack Overflow用户

发布于 2014-12-23 23:00:46

如果您想测试作业是否应该在15分钟后执行,那么您应该将测试用例分成两部分。第一部分,您应该测试它是否插入在15分钟内处于活动状态的作业(使用mocks)。第二部分,作业是否正确执行。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25245417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档