如何使用Rspec Mocks为给定的类存根任何实例

问题描述

|| 以下代码引发错误
undefined method \'any_instance\' for String:Class
require \'rspec\'

RSpec.configure do |config|
  config.mock_with :rspec
end

describe String do
  it \'stubs\' do
    String.any_instance.stub(:foo).and_return(1)
    \'\'.foo.should eq(1)
  end
end
如何将Mocks模块包含在Class或Object类中?     

解决方法

any_instance是最近添加到rspec的,因此您的示例现在对我来说就像rspec 2.7一样适用。 rspec 3的更新: 做到这一点的新方法是
allow_any_instance_of(String).to receive(:foo).and_return(1)
这是更多any_instance文档:https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance     ,使用2.6.0之前的版本的RSpec Mocks,您将无法执行此操作。但是,您可以在Mocha中使用
any_instance
(如此处所示)或在更高版本的Rspec中使用。 在你的
spec/spec_helper.rb
中 确保您具有以下行:
config.mock_with :mocha
没有评论。