测试实例方法调用类方法



简单地说,我有一个带有调用类方法的实例方法的类,我想使用 RSpec 测试在运行实例方法时是否调用了类方法。所以,例如

class Test
  def self.class_method
    #do something
  end
  def instance_method
    #do stuff
    self.class.class_method
  end
end

在 RSpec 中,我尝试了 Test.should_receive(:class_method),但这似乎做了一些奇怪的事情,导致我的测试返回奇怪的行为。如果这就是我应该使用的,也许 RSpec 已经过时了?我正在使用 RSpec 2.7.0。谢谢!

如果你并不真正关心类方法在做什么,只关心它被调用,你可以做这样的事情:

describe Test do
  context '#instance_method' do
    it 'should call the class method' do
      Test.should_receive(:class_method)
      Test.new.instance_method
    end
  end
end

最新更新