Sha256: 0debb7d0b9d42471714bcddfcbb66e9f23dd3acd12536e47ed17c8c87768d47b

Contents?: true

Size: 1.43 KB

Versions: 27

Compression:

Stored size: 1.43 KB

Contents

# Expects a web response to have an error in our given format
RSpec::Matchers.define :have_api_error do |expected_fields|
  match do |response|
    if response.response_code == (expected_fields[:status] || 422)
      error = extract_error(response,expected_fields)
      if error
        expected_code = expected_fields.fetch(:code)
        expected_message = expected_fields.fetch(:message)
        error["code"] == expected_code && message_matches(error["message"],expected_message)
      else
        false
      end
    else
      false
    end
  end

  def extract_error(response,expected_fields)
    parsed_response = JSON.parse(response.body)
    parsed_response["errors"].detect { |error|
      error["code"] == expected_fields.fetch(:code)
    }
  end

  def message_matches(message,expected_message)
    if expected_message.kind_of?(Regexp)
      message =~ expected_message
    else
      message == expected_message
    end
  end

  failure_message do |response|
    expected_status = (expected_fields[:status] || 422)
    if response.response_code != expected_status
      "HTTP status was #{response.response_code} and not #{expected_status}"
    else
      error = extract_error(response,expected_fields)
      if error
        "Expected message to be '#{expected_fields[:message]}', but was '#{error['message']}'"
      else
        "Could not find an error for code #{expected_fields[:code]} from #{response.body}"
      end
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
stitches-5.0.0 lib/stitches/spec/have_api_error.rb
stitches-5.0.0.RC1 lib/stitches/spec/have_api_error.rb
stitches-4.2.2 lib/stitches/spec/have_api_error.rb
stitches-4.2.1 lib/stitches/spec/have_api_error.rb
stitches-4.2.0 lib/stitches/spec/have_api_error.rb
stitches-4.2.0.RC3 lib/stitches/spec/have_api_error.rb
stitches-4.2.0.RC2 lib/stitches/spec/have_api_error.rb
stitches-4.2.0.RC1 lib/stitches/spec/have_api_error.rb
stitches-4.0.2 lib/stitches/spec/have_api_error.rb
stitches-4.1.0RC2 lib/stitches/spec/have_api_error.rb
stitches-4.0.1 lib/stitches/spec/have_api_error.rb
stitches-4.0.0 lib/stitches/spec/have_api_error.rb
stitches-4.0.0.RC1 lib/stitches/spec/have_api_error.rb
stitches-3.8.3 lib/stitches/spec/have_api_error.rb
stitches-3.8.2 lib/stitches/spec/have_api_error.rb
stitches-3.8.1 lib/stitches/spec/have_api_error.rb
stitches-3.8.0 lib/stitches/spec/have_api_error.rb
stitches-3.7.3 lib/stitches/spec/have_api_error.rb
stitches-3.7.2 lib/stitches/spec/have_api_error.rb
stitches-3.7.0 lib/stitches/spec/have_api_error.rb