How to stub any instances for a given class using Rspec Mocks
21,206
Solution 1
any_instance was recently added to rspec, so your example now works for me as it is with rspec 2.7.
Update for rspec 3:
The new way to do this is
allow_any_instance_of(String).to receive(:foo).and_return(1)
Here is more any_instance documentation: https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance
Solution 2
With RSpec Mocks in versions previous to 2.6.0, you cannot do it. However you can use any_instance
with Mocha(as seen here) or in later versions of Rspec.
In your spec/spec_helper.rb
Make sure you have this line:
config.mock_with :mocha
uncommented.
Related videos on Youtube
Author by
Andy
Updated on July 09, 2022Comments
-
Andy almost 2 years
The following code raises an error:
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
How can I include the Mocks module into the Class or Object class?
-
Rein Henrichs about 13 yearsWell, given that the question is "using Rspec Mocks", I'm not sure the answer "don't use Rspec Mocks" is useful. Then again, it's better than the technically correct answer: you can't do it.
-
Andy about 13 yearsThe test above is actually a test from Rspec itself link. And the module AnyInstance gets included through (mocks.rb):
Class.class_eval { include RSpec::Mocks::AnyInstance }
I think there is a way to do it somehow. -
David Chelimsky about 13 yearsThat is the current master but hasn't been released yet. It will be part of the rspec-mocks-2.6.0 release, within the next week or two.
-
lulalala over 12 yearsI am in 2.7.1 but have a similar issue too
-
user650654 over 9 years