[rspec-users] Best way to match several attributes of an object?
Mikel Lindsaar
raasdnil at gmail.com
Thu Apr 8 02:59:28 EDT 2010
>> When you need to check several properties of an object, what is the
>> best way to match them all?
In the mail library I use a custom matcher, which lets me do things like:
it "should handle |Minero Aoki <aamine at loveruby.net>|" do
address = Mail::Address.new('Minero Aoki <aamine at loveruby.net>')
address.should break_down_to({
:display_name => 'Minero Aoki',
:address => 'aamine at loveruby.net',
:local => 'aamine',
:domain => 'loveruby.net',
:format => 'Minero Aoki <aamine at loveruby.net>',
:comments => nil,
:raw => 'Minero Aoki <aamine at loveruby.net>'})
end
The matcher in question is:
# encoding: utf-8
module CustomMatchers
class BreakDownTo
def initialize(expected)
@expected = expected
end
def matches?(target)
@target = target
@failed = false
@expected.each_pair do |k,v|
unless @target.send(k) == @expected[k]
@failed = k
end
end
!@failed
end
def failure_message
"expected #{@failed} to be |#{@expected[@failed]}| " +
"but was |#{@target.send(@failed)}|"
end
def megative_failure_message
"expected #{@failed} not to be |#{@expected[@failed]}| " +
"and was |#{@target.send(@failed)}|"
end
end
# Actual matcher that is exposed.
def break_down_to(expected)
BreakDownTo.new(expected)
end
end
--
http://rubyx.com/
http://lindsaar.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20100408/2becb5ac/attachment.html>
More information about the rspec-users
mailing list