[rspec-users] nil object in mocks

Chris Anderson jchris at mfdz.com
Tue Jan 30 17:36:57 EST 2007


I've been running into some trouble lately when passing mock objects
into rich views. Either I have to obscure my specs by stubbing every
method the view would call on my object, or I have to resort to
trickery like stubbing ActionController#render, which is also less
than ideal.

The solution I've some up with is a variant on the :null_object option
that can be passed to the mock factory. Null objects return themselves
from any unstubbed method call. The option I've added changes that
return value to nil, which doesn't play so well with method chaining,
but does work nicely in most views.

The question for you all is: what should the syntax look like? We've
considered a couple of options but found them lacking. They are

m = mock('returns nil', :nil_object => true)
m = mock('returns nil', :null_object => :returns_nil)

Hopefully someone on the list can come up with something more compelling.

Another idea that just came to me (funny how lunch break has that effect):

m = mock('returns nil', :default => nil)

could be useful like this also

m = mock('returns 5', :default => 5)

and if you allow the default value to be a lambda that takes the mock
as an argument, you can make :null_object a special case:

m = mock('returns self', :default => lambda{|m| m})

but now I'm just getting silly.

Chris Anderson

More information about the rspec-users mailing list