2016-04-25 53 views
2

在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

正確地初始化測試類的正確方法是什麼?

回答

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 

通過與expect(MyServiceObject).to receive(:new).with(object)嘲諷MyServiceObject.new,你覆蓋原實現。但是,要使MyJob#perform正常工作,我們需要MyServiceObject.new返回一個對象 - 您可以使用.and_return(...)執行此操作。

希望這會有所幫助!

+0

很好,謝謝! –

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 
+0

謝謝@adilbiy,我曾經想過一樣。但是,這將返回'NoMethodError:未定義的方法'調用'nil:NilClass'。它導致我的MyServiceObject被初始化,出於某種原因沒有參數。這是100%正確的方法嗎?我的代碼似乎在測試之外正常工作,所以試圖找出問題的所在。 –

+0

我修正了這個例子(現在在評論中增加了'and_return'),這應該解決這個問題。 – mhutter

+0

感謝@mhutter,但我沒有看到您的編輯。你能再發帖嗎? –

相關問題