RSpec 3和sidekiq 3.2.1。我已经正确地设置了sidekiq和rspec-sidekiq。
假设我有一个名为WeatherJob的工作程序,它将把天气状态从sunny更改为rainy
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模拟时间:
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分钟后。但是它没有执行作业?有什么建议吗?谢谢!
发布于 2014-08-12 04:47:47
Sidekiq有三种测试模式:禁用、伪造和内联。默认值是fake,它只是将所有作业推入作业数组中,这就是您所看到的行为。内联模式会立即运行作业,而不是将其排入队列。
要强制Sidekiq在测试期间以内联方式运行作业,请将测试代码包装在Sidekiq::Testing.inline!块中:
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。
发布于 2017-02-13 21:24:47
分两步完成。首先测试作业是否已调度,然后在没有时间延迟的情况下执行作业。下面是一个例子
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
endhave_enqueued_sidekiq_job方法来自于rspec-sidekiq gem。他们在develop分支机构进行了积极的开发。一定要像这样把它包括进去
gem 'rspec-sidekiq', github: "philostler/rspec-sidekiq", branch: "develop"发布于 2014-12-23 23:00:46
如果您想测试作业是否应该在15分钟后执行,那么您应该将测试用例分成两部分。第一部分,您应该测试它是否插入在15分钟内处于活动状态的作业(使用mocks)。第二部分,作业是否正确执行。
https://stackoverflow.com/questions/25245417
复制相似问题