Skip to content

Commit

Permalink
Use a simpler message for identity on singleton expectations
Browse files Browse the repository at this point in the history
  • Loading branch information
Sam Phippen committed Nov 23, 2013
1 parent 0673c19 commit 9dbb578
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 12 deletions.
46 changes: 34 additions & 12 deletions lib/rspec/matchers/built_in/equal.rb
Expand Up @@ -7,17 +7,18 @@ def match(expected, actual)
end

def failure_message_for_should
return <<-MESSAGE
expected #{inspect_object(expected)}
got #{inspect_object(actual)}
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`#{eq_expression}` if you don't care about
object identity in this example.
MESSAGE
@diffable = false
case expected
when FalseClass
builtin_singleton_message("false")
when TrueClass
builtin_singleton_message("true")
when NilClass
builtin_singleton_message("nil")
else
@diffable = true
arbitrary_object_message
end
end

def failure_message_for_should_not
Expand All @@ -31,10 +32,31 @@ def failure_message_for_should_not
MESSAGE
end

def diffable?; true; end
def diffable?
@diffable
end

private

def builtin_singleton_message(type)
"\nexpected #{type}\n got #{inspect_object(actual)}\n"
end

def arbitrary_object_message
return <<-MESSAGE
expected #{inspect_object(expected)}
got #{inspect_object(actual)}
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`#{eq_expression}` if you don't care about
object identity in this example.
MESSAGE
end


def inspect_object(o)
"#<#{o.class}:#{o.object_id}> => #{o.inspect}"
end
Expand Down
21 changes: 21 additions & 0 deletions spec/rspec/matchers/equal_spec.rb
Expand Up @@ -50,6 +50,27 @@ def string.equal?(other)
end
end

it "prints a special message for `false`" do
expected, actual = false, "1"
expect {
expect(actual).to equal(expected)
}.to fail_with "\nexpected false\n got #{inspect_object(actual)}\n"
end

it "prints a special message for `true`" do
expected, actual = true, "1"
expect {
expect(actual).to equal(expected)
}.to fail_with "\nexpected true\n got #{inspect_object(actual)}\n"
end

it "prints a special message for `nil`" do
expected, actual = nil, "1"
expect {
expect(actual).to equal(expected)
}.to fail_with "\nexpected nil\n got #{inspect_object(actual)}\n"
end

it "suggests the `eq` matcher on failure" do
expected, actual = "1", "1"
expect {
Expand Down

0 comments on commit 9dbb578

Please sign in to comment.