Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 310
Andy Avatar asked Apr 12 '11 19:04

Andy


1 Answers

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

like image 114
Melinda Weathers Avatar answered Oct 14 '22 14:10

Melinda Weathers