How to mock when there seems to be a requirement for chained mocked calls?

I want to mock the following:

MyModel.where("…").last

I tried:

MyModel.should_receive(:where).and_return(nil)

but this of course doesn’t match the expectation since the call to .last
was
not mapped in the mock code.

How can I do this?

On Jun 13, 2011, at 8:29 PM, S Ahmed wrote:

“How to mock when there seems to be a requirement for chained mocked
calls?”

There is no such requirement unless you are imposing it by your own
design decisions.

I want to mock the following:

MyModel.where("…").last

Why do you want to do this? Is this in a model spec? A controller spec?

I tried:

MyModel.should_receive(:where).and_return(nil)

but this of course doesn’t match the expectation since the call to .last was not
mapped in the mock code.

How can I do this?

You can stub (not mock) chains like this:

MyModel.stub_chain(:where, :last).and_return(xxx)

You can also set chained expectations like this (but I wouldn’t
recommend it):

ar_query = double(‘ar_query’)
ar_query.should_receive(:last).and_return(nil)
MyModel.stub(:where).and_return(ar_query)

HTH,
David

This is a method in my Model that I am writing a test for correct.

There are allot of if/else clauses in the method, and i want to make
sure
certain things are called so I want to write expectations for it.

Not sure why you don’t recommend such a thing? (chained expecations)

On Jun 13, 2011, at 9:44 PM, S Ahmed wrote:

You can stub (not mock) chains like this:

MyModel.stub_chain(:where, :last).and_return(xxx)

You can also set chained expectations like this (but I wouldn’t recommend it):

ar_query = double(‘ar_query’)
ar_query.should_receive(:last).and_return(nil)
MyModel.stub(:where).and_return(ar_query)

[I moved your post to the bottom]

This is a method in my Model that I am writing a test for correct.

There are allot of if/else clauses in the method, and i want to make sure
certain things are called so I want to write expectations for it.

Not sure why you don’t recommend such a thing? (chained expectations)

Because they are brittle.

You can specify the externally observable behavior of a model without
mocking its internals. This is not the same as setting expectations on
model methods called from controllers, in which case we’re specifying
how one component (the controller) talks to another component (the
model). In a model spec, the model is the component being specified.
That all make sense?

HTH,
David

On 14 June 2011 04:09, David C. [email protected] wrote:

decisions.

it):
There are allot of if/else clauses in the method, and i want to make sure
certain things are called so I want to write expectations for it.

This method will be hard to test because its not a good method. As its
already written you might be better of refactoring first to remove all
the
if/else clauses. The most if/else clauses a method should have is 1!! A
session with the ruby refactoring book is in order :slight_smile: