Forum: RSpec [Rspec] Difference between stub and message expectation with any_number_of_times

1c4303011fdff4c456d0f86306ecb897?d=identicon&s=25 Benyi Wang (Guest)
on 2010-07-13 18:32
(Received via mailing list)
I'm wondering what's the difference between stub and message expectation
with any_number_of_times, for example:

myMock = mock("mymock")
myMock.stub!(:is_a?).with(MyClass).and_return(false)

and

myMock = mock("mymock")
myMock.should_receive(:is_a?).with(MyClass).any_number_of_times.and_return(false)

because is_a? may not be called at all, it just like a stub. Is my
understanding correct?

Is there any guide how to use stub and message expectation?
822a498b26a2cb7d1f0f2e7e37ce61b2?d=identicon&s=25 Ed Howland (Guest)
on 2010-07-14 00:16
(Received via mailing list)
Ok, here is my stab at this:

Since be seem to be only setting and testing bare mocks, I'd assume
this is just useful to pass the mock as a stand in for some other
object. So running a test: [See the code at pastie:
http://pastie.org/1043160
]

I get subtly different messages:

)
Spec::Mocks::MockExpectationError in 'mocking stub should not be ok if
it gets a at least one good argument and an unexpected argument'
Mock "mymock" received unexpected message :is_a? with (NoMock)
./mock_spec.rb:61:

for stubs

vs.
)
Spec::Mocks::MockExpectationError in 'mocking mock should see the
incorrect one and report an error'
Mock "mymock" received :is_a? with unexpected arguments
  expected: (MyClass)
       got: (NoMock)
./mock_spec.rb:28:

for mocks.

The web page says:
"Explicitly Imprecise Counts

my_mock.should_receive(:msg).any_number_of_times
The message can be received 0 or more times.
"

I can't envision a use case where this is needed, or can't be emulated
via a stub.

I'd be interested in David C's take or someone else's.


Cheers,
Ed

Ed Howland
http://greenprogrammer.wordpress.com
http://twitter.com/ed_howland
5d38ab152e1e3e219512a9859fcd93af?d=identicon&s=25 David Chelimsky (Guest)
on 2010-07-14 01:14
(Received via mailing list)
On Jul 13, 2010, at 11:29 AM, Benyi Wang wrote:

> because is_a? may not be called at all, it just like a stub. Is my understanding 
correct?
Yes.

> Is there any guide how to use stub and message expectation?

any_number_of_times was introduced before we introduced stubs, way back,
way back. I use stub() rather than should_receive + any_number_of_times.

HTH,
David
This topic is locked and can not be replied to.