gpt4 book ai didi

ruby - 使用 RSpec 3 测试 sidekiq perform_in

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:44 24 4
gpt4 key购买 nike

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

假设我有一个名为 WeatherJob 的 worker,它将天气状态从 sunny 更改为 rainy:

class WeatherJob
include Sidekiq::Worker

def perform record_id
weather = Weather.find record_id

weather.update status: 'rainy'
end
end

我这样使用这个 worker:

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 分钟后。但是它没有执行作业?有什么建议吗?谢谢!

最佳答案

Sidekiq 具有三种测试模式:disabledfakeinline。默认值为 fake,它只是将所有作业推送到作业数组中,这就是您所看到的行为。 内联 模式立即运行作业而不是将其排队。

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

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 .

关于ruby - 使用 RSpec 3 测试 sidekiq perform_in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25245417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com