[rspec-devel] Better inspect method for active record objects in rspec-rails

Jeff Dean jdean at pivotallabs.com
Sun Nov 2 22:51:52 EST 2008

I'm working on a rails project where we have a complex object graph  
and often find ourselves having to assert on the exact contents of  
arrays of ActiveRecord objects.   Several of our tables have 20+  
fields, so calling @person.inspect generates a very lengthy string.

A recent post suggested mapping/collecting certain fields to shorten  
the error message and make things look prettier.  Since the only thing  
in question here is what the error message looked like, I thought it  
could be useful to have RSpec look for a custom inspect method first  
(say, rspec_inspect), and call it if it's there - defaulting to  
inspect.  So a spec_helper might look like this:

Person.class_eval do
   def rspec_inspect
     "<#{name} (#{id || 'new_record'})>"

Then, whenever you call include, the error message would look like:

expected [<Jane (2)>, <Fred (3)>] to include [<Joe (new record)>]

Since the override would happen in a spec helper, we wouldn't have to  
mess with AR's inspect method at all and we wouldn't have to map/ 
collect for good error messages.

As far as making it happen, I would suggest:

Alias rspec_inspect to inspect on object, so everything has it by  
default (we could go with checking if it the object responds_to  
rspec_inspect, which would cleaner but slower as well)
Adding new examples to every matcher spec
Change all calls to inspect in all of the matcher error messages and  
descriptions to call rspec_inspect (and anywhere else that objects are  
Writing some developer documentation/wiki page entries to alert future  
developers to the pattern

Mike Grafton also suggested (although somewhat jokingly) that we could  
call it inspec instead of rspec_inspect.  I like that idea a lot.

I'd be willing to put the leg work in to creating a patch if people  
think it would be useful and a likely candidate for inclusion.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-devel/attachments/20081102/2fadd946/attachment.html>

More information about the rspec-devel mailing list