Last active
March 11, 2018 11:37
-
-
Save nbulaj/7c90dc0881a4100a865937f24e1a711e to your computer and use it in GitHub Desktop.
More informative RSpec #be_success matcher with negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# spec/rails_helper.rb or spec/spec_helper.rb | |
# ... | |
# require custom matchers from the "support" directory: | |
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } | |
# ----- | |
# support/matchers/be_success.rb | |
RSpec::Matchers.define :be_success do | |
match do |actual| | |
actual.success? | |
end | |
failure_message do |actual| | |
"expected to be success, but it is not\n\n#{data_for_response(actual)}" | |
end | |
failure_message_when_negated do |actual| | |
"expected that response would not be success, but it is\n\n#{data_for_response(actual)}" | |
end | |
private | |
def data_for_response(response) | |
request = response.request | |
"Request path: #{request.request_method} #{request.fullpath}\n\n" \ | |
"Request params: #{prettify_json(request.request_parameters.to_json)}\n\n" \ | |
"Response status: #{response.status}\n\n" \ | |
"Response body: #{prettify_json(response.body)}" | |
end | |
def prettify_json(json) | |
JSON.pretty_generate(JSON.parse(json)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment