Stubbing method on any instance of object and return different results fails

615 views
Skip to first unread message

Panayotis Matsinopoulos

unread,
Feb 16, 2014, 1:13:41 PM2/16/14
to rs...@googlegroups.com
Hi,

What am I doing wrong here?

I am trying to stub a method on any instance of an object and return different results and this fails.

Here is the project that demonstrates this particular bug(?).


(clone and run "bundle exec rspec"...you will see the failure)

Let me know if I am doing something wrong

Thanks in advance

Panayotis




Aaron Kromer

unread,
Feb 16, 2014, 1:34:44 PM2/16/14
to rs...@googlegroups.com

Your call to and_return(500, 100) is being set on each new OtherFooClass instance. It is not a stub shared by all instances. So in your example, each new instance of OtherFooClass will return 500 the first time you call other_foo and then 100 on all subsequent calls.

My 2cents: do not use allow_any_instance_of. Instead setup explicit doubles for each new instance. Something like:

foo1 = double(OtherFooClass, other_foo: 500)
foo2 = double(OtherFooClass, other_foo: 100)
allow(OtherFooClass).to receive(:new).and_return(foo1, foo2)

IF you really must use any_instance you’ll need to keep track of the return values. By manipulating the block form of and_return along with a closure you can achieve this with:

return_values = [500, 100]
allow_any_instance_of(OtherFooClass).to receive(:other_foo).and_return{
  return_values.shift
}

For completeness, receive could also be passed the block to achieve the same result.

Aaron



--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/71a081d4-c6a0-4227-bd3b-38d6697e4369%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Panayotis Matsinopoulos

unread,
Feb 16, 2014, 1:59:31 PM2/16/14
to rs...@googlegroups.com
I tried the block form of `and_return` along with a closure and it worked.

Thanks a lot
Panayotis
Reply all
Reply to author
Forward
0 new messages