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

David Chelimsky dchelimsky at gmail.com
Mon Nov 3 07:15:40 EST 2008

On Sun, Nov 2, 2008 at 9:51 PM, Jeff Dean <jdean at pivotallabs.com> wrote:
> 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'})>"
>   end
> end
> 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
> inspected)
> 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.
> Thoughts?
> Jeff

Hey Jeff,

I'm all for solving this problem, though I have some different ideas
about the approach.

Would you mind posting this request to lighthouse so we can have the
conversation there?


More information about the rspec-devel mailing list