Today I Learned

hashrocket A Hashrocket project

Append an RSpec Failure Message

Have you ever wanted to customize an RSpec failure message? It’s possible, but we lose the original message. What if we want both?

Here’s one technique:

  expect(actual).to eq(expected)
rescue RSpec::Expectations::ExpectationNotMetError
  $!.message << <<-MESSAGE

You broke it.

Maybe you deleted the fixtures? Try running `rake db:create_fixtures`.

This rescues the failure ExpectationNotMetError, then shovels our HEREDOC string onto the message of $!, a built-in Ruby global variable representing the last error. Then, we raise.

The result is our RSpec error, with the provided message, followed by our custom text.

See More #testing TILs