any_instance does not work when called inside of a before block #60

Closed
thhermansen opened this Issue May 20, 2011 · 6 comments

Comments

Projects
None yet
6 participants

I have the following code which does not work. Version 2.6.0.

describe "foo" do
  before do
    Object.any_instance.stub(:foo).and_return(:return_value)
  end

  it "any_instance" do
    o = Object.new
    o.foo.should eq(:return_value)
  end    
end

before(:all) has the same outcome. I get:

Failures:

1) foo any_instance
Failure/Error: Object.any_instance.stub(:foo).and_return(:return_value)
NoMethodError:
undefined method `any_instance' for Object:Class

If I put the any_instance call inside of the it-block it is working as expected. Is it supposed to work? :-)

Owner

dchelimsky commented May 20, 2011

before(:all) should not work, but before(:each) should.

Thanks, confirming that before(:each) do work. Have no idea how I managed to being able to make it fail with the code I pasted above. Maybe I didn't manage to save file after changing before(:all) to :each or something stupid. Oh my fault. Thanks again! :-)

If it is possible to support before(:all), I think this issue should be re-opened. If it's just not possible, please add a runtime warning, or add a note to that effect in the docs.

https://www.relishapp.com/rspec/rspec-mocks/v/2-9/docs/method-stubs/stub-on-any-instance-of-a-class

👍
I agree, this is very confusing, there should be a warning.

Contributor

alindeman commented Nov 11, 2012

Nothing mocking related should be done in a before(:all). These docs cover it: https://www.relishapp.com/rspec/rspec-mocks/v/2-11/docs/scope

Owner

myronmarston commented Nov 11, 2012

A random thought I just had: if we can come up with good solutions for both rspec/rspec-core#573 and rspec/rspec-mocks#153, we can get things to a point where users aren't even allowed to try to setup a mock or stub in before(:all), which would help reduce the confusion here. Consider that if we replace before(:all) with a new construct (e.g. before(:group)) which doesn't share state, it's fairly intuitive that before(:group) blocks aren't eval'd in the same context as examples. Combine that with a new syntax for mocking that doesn't globally add methods to objects that allow them to be mocked or stubbed from anywhere but rather only makes mocking available by wrapping an object with on, allow, expect or something similar...and we can make those methods only available in the example and before(:each) contexts, but not the before(:group) context.

It's something to consider, at least.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment