gpt4 book ai didi

ruby-on-rails - RSpec + Sidekiq : NoMethodError: undefined method 'jobs' MyImportJob

转载 作者:行者123 更新时间:2023-12-02 17:12:16 28 4
gpt4 key购买 nike

我正在尝试在 Rails 4.2.4 应用程序中为 RSpec + Sidekiq 编写一些规范,但遇到了一些问题。

我的代码是这样的:

class MyImportJob
include Sidekiq::Worker
sidekiq_options queue: :default

def perform(params)
# Do magic
end
end

和规范:

describe MyImportJob, type: :job do
let(:panel) { create(:panel) }

describe '#perform' do
context 'unsuccessfully' do
it 'raises ArgumentError if no panel param was passed' do
expect {subject.perform_async()}.to raise_error(ArgumentError)
end
end

context 'successfully' do
it 'given a panel, it increases the job number' do
expect {
subject.perform_async(panel_id: panel.id)
}.to change(subject.jobs, :size).by(1)
end
end
end
end

但我收到以下错误:

Failure/Error: }.to change(subject.jobs, :size).by(1)
NoMethodError:
undefined method `jobs' for #<MyImportJob:0x007f80b74c5c18>

Failure/Error: expect {subject.perform_async()}.to raise_error(ArgumentError)
expected ArgumentError, got #<NoMethodError: undefined method `perform_async' for #<MyImportJob:0x007f80b6d73f50>>

我相信 perform_async 应该由 Sidekiq 默认提供,只要我在我的 worker 中包含行 include Sidekiq::Worker ,这是正确的吗?如果我只使用 perform,第一个测试会通过,但我希望它能通过 perform_async,这正是我在我的代码库中使用的。

至于第二个,我不明白为什么测试对象没有方法jobs。有什么线索吗?

我的 rails_helper.rb 文件有:

require 'sidekiq/testing'
Sidekiq::Testing.fake!

提前致谢!

最佳答案

如果您没有明确定义subject,rspec 将按照以下规则创建主题:

By default, if the first argument to an outermost example group (describe or context block) is a class, RSpec creates an instance of that class and assigns it to the subject

引用:What's the difference between RSpec's subject and let? When should they be used or not?

这意味着它会创建您的 worker 的实例。这样就不能调用perform_asyncjobs

要解决您的问题,请明确定义如下:

describe MyImportJob, type: :job do
let(:panel) { create(:panel) }

subject { MyImportJob }

describe '#perform' do
context 'unsuccessfully' do
it 'raises ArgumentError if no panel param was passed' do
expect {subject.perform_async()}.to raise_error(ArgumentError)
end
end

context 'successfully' do
it 'given a panel, it increases the job number' do
expect {
subject.perform_async(panel_id: panel.id)
}.to change(subject.jobs, :size).by(1)
end
end
end
end

关于ruby-on-rails - RSpec + Sidekiq : NoMethodError: undefined method 'jobs' MyImportJob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48546481/

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