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

问题描述 投票:0回答:3

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

不起作用。

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

ruby-on-rails rspec
3个回答
11
投票

你存根错误。你的

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。


3
投票

您应该能够在要创建其实例的类上存根该方法。 例如

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
投票

这是一个老问题了,但是搜索

rspec rails stub a method
时仍然会弹出。

虽然

allow_any_instance_of
expect_any_instance_of
都可以在这种情况下工作,但由于多种原因,这被认为是臭代码。

我在实现@Taryn 的答案时遇到了困难,但我的问题是如何声明测试实例。

class Z
   include YYY
end

def outer_test
   Z.new
end

describe Z do

  def inner_test
     Z.new
  end

  # this passes
  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

  # these will not
  describe "Z#a_method" do
    it 'returns a' do
      expect(outer_test).to receive(:enabled?).and_return(true)
      expect(outer_test.a_method).to eq('a')
    end
  end

  describe "Z#a_method" do
    it 'returns a' do
      expect(inner_test).to receive(:enabled?).and_return(true)
      expect(inner_test.a_method).to eq('a')
    end
  end


end

我需要小心确保测试类实例声明是在

let
块中完成的,这样类型的存根才能成功。但是
allow_any_instance_of
expect_any_instance_of
都将允许那些失败的测试通过。

© www.soinside.com 2019 - 2024. All rights reserved.