Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

rspec

Here is the class that I'm testing contained in Foo.rb:

class Foo
    def bar
        return 2
    end
end

Here is the 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 am getting 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've consulted the doc and the example given is passing on my machine (so it isn't a problem with the rspec code), but it isn't giving me any information on what I might be doing wrong. The error message is also quite confusing as it's telling me not to call .any_instance on a nil:NilClass, but as I proved with my output, Foo isn't nil. How am I supposed to call .any_instance.stub on my custom object?

I'm using Ruby 1.9.3 and rspec 2.14.5.

like image 204
Seanny123 Avatar asked Sep 11 '13 11:09

Seanny123


2 Answers

You should use before(:each) for stubbing.

Stubs in before(:all) are not supported. The reason is that all stubs and mocks get cleared out after each example, so any stub that is set in before(:all) would work in the first example that happens to run in that group, but not for any others.

rspec-mocks readme

like image 182
valeronm Avatar answered Nov 15 '22 19:11

valeronm


From Rspec 3 any_instance is not defined anymore.

Now use:

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

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

like image 45
Riiwo Avatar answered Nov 15 '22 17:11

Riiwo