[rspec-users] stub_chain together with should_receive

David Chelimsky dchelimsky at gmail.com
Wed Nov 24 08:38:46 EST 2010

On Nov 23, 2010, at 7:12 PM, medihack wrote:

> Hello.
> I am trying to test if in a method calling chain one of the methods
> get a specific parameter. In the below code for example MyModel must
> receive the parameter 0 for the method "offset". Unfortunately the
> code below does not work. It seems it is not possible to mix
> should_receive and stub_chain. How could I solve this?
> MyModel.should_receive(:offset).with(0).stub_chain(:tag_counts, :offset, :limit, :order).and_return([])
> # does not work!

As you're finding out, chains like this are hard to test. That, and the fact that writing code before tests significantly increases the likelihood that the code will be hard to test.

There is no easy way to do what you're trying to do with this code. You'd have to create a series of test doubles, like this:

offset_return_value = double
offset_return_value.stub_chain("limit.order") { [] }
tag_counts_return_value = double
MyModel.stub(:tag_counts) { tag_counts_return_value }

The problem with this sort of structure, besides it being hard to read, is that you can't change anything about the implementation of the method that is invoking this chain without changing this example and likely many others.

I'd recommend wrapping that chain in a method and specifying how that method behaves when a 0 makes its way to the offset method vs how it behaves otherwise.


> Regards,
> Kai
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users


More information about the rspec-users mailing list