2014-09-01 25 views
1

我想嘗試測試對象是否在特定情況下使用優化。所以,我有這種代碼Ruby Rspec3期望一次接收內部方法調用

class Bar 
    attr_reader :n 
    def initialize(n) 
    @n=n 
    end 

    def a 
    if @n <= 3 
     b1 
    else 
     b2 
    end 
    end 

    def b1 
    @n+=1 
    end 

    def b2 
    @n+=1 ##super fast addition 
    end 
end 

我嘗試寫這樣的一個rspec的

bar=Bar.new(5) 
allow(bar).to receive(:b2).and_call_original 

bar.a 
expect(bar).to receive(:b2).once 
expect(bar.n).to eq 6 

但它不工作...你kown這可能嗎?如果是的話,怎麼樣?

回答

2

您應該將receive期望之前的方法調用。您也可以將allowexpect合併爲一行:

bar = Bar.new(5) 
expect(bar).to receive(:b2).once.and_call_original 
bar.a 
expect(bar.n).to eq 6 
+0

謝謝,我現在的測試工作 – ebuprofen 2014-09-02 15:46:16