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

问题描述 投票:18回答:2

以下代码引发错误: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类中?

ruby mocking rspec
2个回答
31
投票

any_instance最近被添加到rspec,所以你的例子现在适用于我,因为它与rspec 2.7一样。

Update for 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


3
投票

在2.6.0之前的版本中使用RSpec Mocks,你无法做到。但是你可以使用any_instance和Mocha(见here)或更高版本的Rspec。

在你的spec/spec_helper.rb

确保你有这一行:

config.mock_with :mocha

注释。

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