[rspec-users] lots of nil problems!

Tom Stuart tom at experthuman.com
Sat Mar 20 07:41:29 EDT 2010

Hi David,

On 20 Mar 2010, at 10:42, David Chelimsky wrote:
> There is an alternate syntax that I'm using nearly exclusively at this
> point, which is to pass a block along with the stub() and
> should_receive() messages:
> [...]
> I've been thinking of deprecating the and_xxx methods in rspec-2. Does
> anybody think that's an awful idea?

I don't think it's an awful idea -- less API is a laudable goal -- but I dislike it for two reasons:

1. I like the symmetry of ".with(...).and_return(...)". The alternative of ".with(...) { ... }" feels weird, lopsided and misleadingly implicit to me; #with is "merely configuration" too, so why does #and_return get the special treatment?

2. I like the semantics of #and_return, i.e. its argument gets eagerly evaluated by Ruby (at "stub time") and the return value sits there waiting to be returned whenever the stubbed message is received. I'm uncomfortable about *always* specifying the return value by providing a block whose evaluation happens later (at "message time") and potentially has side-effects, argument-dependent behaviour etc. I appreciate that #stub and #should_receive already give you the ability to pass a block for this purpose, and that's occasionally useful, but I much prefer being able to explicitly choose that style when it's absolutely necessary (e.g. when I absolutely must have a "dynamic stub" whose return value actually depends upon its arguments) but this is very much the exception rather than the rule. (Quoth rspec.info: "While this is possible, it is generally to be avoided. Calculating a value to return defeats the declarative nature of stubs.") It's nice to be able to see the difference syntactically rather than having to inspect the behaviour of the block to see whether it's doing anything clever; namely, #and_return serves as a nice annotation that you're doing "the normal thing".

So basically I suspect that your proposal makes it easier for RSpec newbies to learn the API since the block form is potentially less surprising and "more Ruby", but I fear that it also makes things less explicit and therefore harder to understand & maintain further down the road.


More information about the rspec-users mailing list