Rspec any_instance.stub calls the undefined method `any_instance_recorder_for 'for nil: NilClass exception

Here is the class I am testing contained in Foo.rb :

class Foo def bar return 2 end end 

Here is my test contained in Foo_spec.rb :

 require "./Foo.rb" describe "Foo" do before(:all) do puts "#{Foo == nil}" Foo.any_instance.stub(:bar).and_return(1) end it "should pass this" do f = Foo.new f.bar.should eq 1 end end 

I get the following output:

 false F Failures: 1) Foo Should pass this Failure/Error: Foo.any_instance.stub(:bar).and_return(1) NoMethodError: undefined method `any_instance_recorder_for' for nil:NilClass # ./Foo_spec.rb:6:in `block (2 levels) in <top (required)>' Finished in 0 seconds 1 example, 1 failure Failed examples: rspec ./Foo_spec.rb:9 # Foo Should pass this 

I have advised a document and the above example runs on my machine (so this is not a problem with the rspec code), but it does not give me any information about what I may be doing wrong. The error message is also rather confusing, as it tells me not to call .any_instance on nil:NilClass , but, as I proved with my output, Foo not nil . How can I call .any_instance.stub on my custom object?

I am using Ruby 1.9.3 and rspec 2.14.5 .

+8
ruby rspec
source share
3 answers

You must use before(:each) to crop.

Supports in before(:all) not supported. The reason is that all stubs and layouts are cleared after each example, so any stub installed in before(:all) will work in the first example that runs in this group, but not for others.

rspec-mocks readme

+27
source share

From Rspec 3, any_instance is no longer defined.

Now use:

 allow_any_instance_of(Foo).to receive(:bar).and_return(1) 

Source for this and earlier versions: https://makandracards.com/makandra/2561-stub-methods-on-any-instance-of-a-class-in-rspec-1-and-rspec-2

+1
source share

The rspec update worked for me. You can do this using the following command:

bundle update rspec

0
source share

All Articles