以下代码引发错误: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一样。
这样做的新方法是
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,你无法做到。但是你可以使用any_instance
和Mocha(见here)或更高版本的Rspec。
在你的spec/spec_helper.rb
确保你有这一行:
config.mock_with :mocha
注释。