Rspec如何存根模块实例方法?

时间:2016-04-21 04:04:03

标签: ruby-on-rails rspec

B.rb看起来像:

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

它没有用。

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

2 个答案:

答案 0 :(得分:3)

你错了。您的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 方法,因此您需要使用此方法:

enabled?

然后在调用:a_method时,p将返回true。

答案 1 :(得分: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

或类似......

相关问题