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

时间:2011-04-12 19:57:11

标签: ruby mocking rspec

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

2 个答案:

答案 0 :(得分:31)

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

答案 1 :(得分:3)

在2.6.0之前的版本中使用RSpec Mocks,你无法做到。但是,您可以将any_instance与Mocha(如here所示)或更高版本的Rspec一起使用。

spec/spec_helper.rb

确保你有这一行:

config.mock_with :mocha

注释。

相关问题