From 3251c6589d31bc931ee3a98c5c47e16eedd82b97 Mon Sep 17 00:00:00 2001 From: Vesa Laakso <482561+valscion@users.noreply.github.com> Date: Sun, 12 Jan 2020 12:07:45 +0200 Subject: [PATCH] Add better debuggability to be_X test failures (#134) * Add better debuggability to be_X test failures This way test failures will show what the HTTP status code actually was when test fails as well as output the entire response body. The response body will most likely contain vital debugging information to help figure out why the test failed * Output last request information on spec failures --- spec/support/custom_matchers.rb | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 spec/support/custom_matchers.rb diff --git a/spec/support/custom_matchers.rb b/spec/support/custom_matchers.rb new file mode 100644 index 00000000..8a2f9681 --- /dev/null +++ b/spec/support/custom_matchers.rb @@ -0,0 +1,54 @@ +# Add better debuggability to be_forbidden failures +RSpec::Matchers.define :be_forbidden do + match(&:forbidden?) + + failure_message do |actual| + debug_text_for_failure('forbidden', response: actual, last_request: last_request) + end +end + +# Add better debuggability to be_not_found failures +RSpec::Matchers.define :be_not_found do + match(&:not_found?) + + failure_message do |actual| + debug_text_for_failure('not_found', response: actual, last_request: last_request) + end +end + +# Add better debuggability to be_unprocessable failures +RSpec::Matchers.define :be_unprocessable do + match(&:unprocessable?) + + failure_message do |actual| + debug_text_for_failure('unprocessable', response: actual, last_request: last_request) + end +end + +# Add better debuggability to be_successful failures +RSpec::Matchers.define :be_successful do + match(&:successful?) + + failure_message do |actual| + debug_text_for_failure('successful', response: actual, last_request: last_request) + end +end + +# Add better debuggability to be_ok failures +RSpec::Matchers.define :be_ok do + match(&:ok?) + + failure_message do |actual| + debug_text_for_failure('ok', response: actual, last_request: last_request) + end +end + +def debug_text_for_failure(expected, response:, last_request:) + debug_text = "expected response to be #{expected} but HTTP code was #{response.status}." + debug_text += " Last request was #{last_request.request_method} to #{last_request.fullpath}" + unless last_request.get? + debug_text += " with body:\n" + last_request.body.read + end + debug_text += "\nResponse body was:\n" + response.body + debug_text +end