-
-
Save tb/7040353 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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