2016-04-21 26 views
3

B.rb樣子:Rspec如何存根模塊實例方法?

module A 
    module B 

    def enabled? xxx 
     xxx == 'a' 
    end 

    def disabled? xxx 
     xxx != 'a' 
    end 
    end 
end 

另一個C.rb像:

module YYY 
    class C 
    include A::B 

    def a_method 
    if(enabled? xxx) 
     return 'a' 
    return 'b' 
    end 
end 

現在我想要寫單元測試來測試a_method功能,

describe :a_method do 
    it 'returns a' do 
     ###how to sub enabled? method to make it return true.... 
    end 
end 

啓用?是模型中的實例方法,我試過

A::B.stub.any_instance(:enabled).and_return true 

它不起作用。

任何人都可以幫助我????

回答

1

你磕碰錯誤。你的A::B是一個模塊,所以你沒有實例,實例是類。你也忘記了問號。

試試這個存根你的模塊靜態方法:

A::B.stub(:enabled?).and_return true 

而在第二個例子中(如果需要)試試這個:

YYY::C.any_instance.stub(:a_method).and_return something 

但我認爲你正試圖存根enabled?方法YYY::C,所以你需要使用這個:

YYY::C.any_instance.stub(:enabled?).and_return true 

然後當調用:a_method時,enabled?將返回true。

1

您應該能夠在創建實例的類上存根方法。 如

class Z 
    include YYY 
end 

describe Z do 
    describe "Z#a_method" do 
    let(:z) { Z.new } 
    it 'returns a' do 
     expect(z).to receive(:enabled?).and_return(true) 
     expect(z.a_method).to eq('a') 
    end 
    end 
end 

或類似...

+0

是否有另一種方法,如果我想存根模塊實例方法? –

+0

我想你需要幫助我們理解爲什麼你需要按照你想要的方式去做,然後才能以其他方式提供幫助。 –

+0

'A :: B.stub.any_instance(:enabled).and_return true'似乎存在兩個問題:1)該方法被啓用?不啓用2)模塊沒有真正的實例...類做。所以要存根類的實例...你必須有一個包含模塊的類。順便說一下:與實際製作實例並測試它相比,'any_instance _of'是一種昂貴的使用方法。這就是我按照上面的方式做到這一點的原因。上述方式是測試的標準方式... –