我正在嘗試測驗被另一種方法呼叫的方法。我不想測驗其他方法的作用,因為這是一個單獨的單元測驗。
所以假設我有類似的東西:
class MyService
def method_a
a = 1
b = method_b
return a b
end
def method_b
return 2
end
end
現在,我想測驗 method_a - 我想驗證 method_b 是否已執行。
我知道如果方法是靜態的,這應該可以作業。但就我而言,它不是靜態的。
allow(MyService).to receive(:method_b)
我不斷收到此錯誤:
MyService does not implement method_b
我知道這是因為該方法不是靜態的,但我在檔案中找不到任何適合我用例的內容。
uj5u.com熱心網友回復:
我認為主要問題是您期望呼叫類方法而不是實體
describe MyService do
it "should call method_b" do
expect(subject).to receive(:method_b).and_return(2)
subject.method_a
end
end
# P.S. it's the same as:
describe MyService do
it "should call method_b" do
service = MyService.new # instead of MyService.new you can also write described_class.new
expect(service).to receive(:method_b).and_return(2)
service.method_a
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/493381.html
標籤:轨道上的红宝石 红宝石 rspec rspec-rails
上一篇:如何讓兩個Ruby程式相互通信
