How to stub any instances for a given class using Rspec Mocks How to stub any instances for a given class using Rspec Mocks ruby ruby

How to stub any instances for a given class using Rspec Mocks


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 isallow_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


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.