在Rails应用程序中,我有一个调用服务对象的后台作业
class MyJob < ActiveJob::Base
def perform( obj_id )
return unless object = Object.find(obj_id)
MyServiceObject.new(object).call
end
end
我可以测试该作业如下调用服务对象:
describe MyJob, type: :job do
let(:object) { create :object }
it 'calls MyServiceObject' do
expect_any_instance_of(MyServiceObject).to receive(:call)
MyJob.new.perform(object)
end
end
但是如何测试作业是否使用正确的参数初始化服务对象?
describe MyJob, type: :job do
let(:object) { create :object }
it 'initializes MyServiceObject with object' do
expect( MyServiceObject.new(object) ).to receive(:call)
MyJob.new.perform(object)
end
end
我希望实现上述内容,但这会失败expects 1 but received 0
。
正确初始化测试类的正确方法是什么?
答案 0 :(得分:2)
显然我对Adilbiy的答案的解决方案被拒绝了,所以这是我的最新答案:
describe MyJob, type: :job do
let(:object) { create :object }
it 'initializes MyServiceObject with object' do
so = MyServiceObject.new(object)
expect(MyServiceObject).to receive(:new).with(object).and_return(so)
MyJob.new.perform(object)
end
end
通过使用MyServiceObject.new
模拟expect(MyServiceObject).to receive(:new).with(object)
,您将覆盖原始实现。但是,要使MyJob#perform
生效,我们需要MyServiceObject.new
来返回一个对象 - 您可以使用.and_return(...)
执行此操作。
希望这有帮助!
答案 1 :(得分:0)
我可能会建议进行以下测试:
describe MyJob, type: :job do
let(:object) { create :object }
it 'initializes MyServiceObject with object' do
expect( MyServiceObject).to receive(:new).with(object)
MyJob.new.perform(object)
end
end