2011-03-11 62 views
1

我有這樣一個構造函數:如何測試在一個構造方法調用使用RSpec

class Foo 
    def initialize(options) 
    @options = options 
    initialize_some_other_stuff 
    end 
end 

,並想一個實例化一個新的Foo對象的通話測試,以initialize_some_other_stuff

我覺得這個問題rspec: How to stub an instance method called by constructor?但建議的解決方案調用Foo.any_instance(:initialize_some_other_stuff)不起作用在我的rspec版本(2.5.0)。

任何人都可以幫助我測試這個構造函數嗎?

回答

0

在你SPEC,你可以有以下幾點:

class Foo 
    attr_reader :initializer_called 
    def initialize_some_other_stuff 
    @initializer_called = true 
    end 
end 

foo = Foo.new 
foo.initializer_called.should == true 

如果構造函數調用initiaize_some_other_stuff方法,foo.initializer_called應該是真實的。

+0

嗨gnab,THX你的答案。問題是,我不想調用'initialize_some_other_stuff'方法,我想嘲笑它。 – Andi 2011-03-13 12:08:33

+0

我明白了。我發佈的代碼有效地用dummy(模擬)代替'initialize_some_other_stuff',並添加了一些功能來確定它是否被調用,因爲我們無法爲此調用任何監聽器,因爲調用發生在構造函數中。你原來的'initialize_some_other_stuff'永遠不會被調用。 – gnab 2011-03-13 12:25:22

0

在這裏你去:

stub_model(美孚).should_receive(:some_method_call)。隨着(optional_argument)