Skip to content

Instantly share code, notes, and snippets.

@wjlroe
Created March 20, 2023 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjlroe/15e18f5840f66609e1b677d814febcdf to your computer and use it in GitHub Desktop.
Save wjlroe/15e18f5840f66609e1b677d814febcdf to your computer and use it in GitHub Desktop.
Show RSpec's unhelpful error output when combining matchers
require 'rspec'
Person = Struct.new(:name, :age)
RSpec.describe do
subject { Person.new("Bob", 32) }
it { is_expected.to have_attributes(name: "Bob", age: 33) }
# ^ This failure prints the attributes diff as follows:
# 1) is expected to have attributes {:age => 33, :name => "Bob"}
# Failure/Error: it { is_expected.to have_attributes(name: "Bob", age: 33) }
#
# expected #<struct Person name="Bob", age=32> to have attributes {:age => 33, :name => "Bob"} but had attributes {:age => 32, :name => "Bob"}
# Diff:
# @@ -1 +1 @@
# -:age => 33,
# +:age => 32,
#
# # ./test_have_attributes_and.rb:9:in `block (2 levels) in <top (required)>'
it { is_expected.to be_a(Person).and have_attributes(name: "Bob", age: 33) }
# ^ This failure prints the whole object rather than the attribute diff
# 2) is expected to be a kind of Person and have attributes {:age => 33, :name => "Bob"}
# Failure/Error: it { is_expected.to be_a(Person).and have_attributes(name: "Bob", age: 33) }
#
# expected #<struct Person name="Bob", age=32> to have attributes {:age => 33, :name => "Bob"} but had attributes {:age => 32, :name => "Bob"}
# Diff for (have attributes {:age => 33, :name => "Bob"}):
# @@ -1,3 +1,2 @@
# -:age => 33,
# -:name => "Bob",
# +"#<struct Person name=\"Bob\", age=32>"
#
# # ./test_have_attributes_and.rb:12:in `block (2 levels) in <top (required)>'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment