Jua*_*tas 4 ruby rspec sidekiq rspec-sidekiq
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
Run Code Online (Sandbox Code Playgroud)
我像这样使用这个工人:
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
Run Code Online (Sandbox Code Playgroud)
我可以看到Weather.jobs阵列中有工作.时间恰好是16分钟后.但它没有执行这项工作?有什么建议吗?谢谢!
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
Run Code Online (Sandbox Code Playgroud)
有关测试Sidekiq的更多信息,请参阅官方测试维基页面.
分两步进行。首先测试作业是否已调度,然后无时间延迟地内联执行作业。这是一个例子
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
Run Code Online (Sandbox Code Playgroud)
have_enqueued_sidekiq_job方法来自rspec-sidekiq gem。他们在分支机构正在进行积极的发展develop。确保你像这样包含它
gem 'rspec-sidekiq', github: "philostler/rspec-sidekiq", branch: "develop"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5341 次 |
| 最近记录: |