Skip to content

Instantly share code, notes, and snippets.

@tb
Forked from ubermajestix/inspector.rb
Created October 18, 2013 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tb/7040353 to your computer and use it in GitHub Desktop.
Save tb/7040353 to your computer and use it in GitHub Desktop.
# When an RSpec test like this fails,
#
# @my_array.should == [@some_model, @some_model2]
#
# RSpec will call inspect on each of the objects to "help" you figure out
# what went wrong. Well, inspect will usually dump a TON OF SHIT and make trying
# to figure out why `@my_array` is not made up of `@some_model` and `@some_model2`
# really really painful.
#
# This little module and technique helps get around that. It will redefine `inspect`
# when you include it in any object.
#
# You can define a whitelist of methods that inspect will dump, and it will always
# provide `object_id` at a minimum.
#
# To use it, drop it in spec/support/inspector.rb and class_eval the models that
# you need override `inspect` on!
#
# Thanks to Jeff at PivotalLabs Boulder for showing me the basic technique.
#
module Inspector
def inspect
string = "<#{self.class.name}:#{self.object_id} "
fields = self.class.inspector_fields.map{|field| "#{field}: #{self.send(field)}"}
string << fields.join(", ")
end
def self.included source
$stdout.puts "Overriding inspect on #{source}"
source.class_eval do
def self.inspector *fields
@inspector_fields = *fields
end
def self.inspector_fields
@inspector_fields ||= []
end
end
end
end
SomeModel.class_eval do
include Inspector
inspector :id, :title
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment