lib/airborne/request_expectations.rb in airborne-0.1.8 vs lib/airborne/request_expectations.rb in airborne-0.1.9

- old
+ new

@@ -1,9 +1,10 @@ require 'rspec' require 'date' module Airborne + class ExpectationError < StandardError; end module RequestExpectations include RSpec include PathMatcher def expect_json_types(*args) @@ -128,11 +129,13 @@ return expect_type(expectations, hash_or_value.class) if expectations.class == Symbol return expectations.call(hash_or_value) if expectations.class == Proc expectations.each do |prop_name, expected_type| - value = expected_type == :date ? convert_to_date(hash_or_value[prop_name]) : hash_or_value[prop_name] + value = ensure_hash_contains_prop(prop_name, hash_or_value) do + expected_type == :date ? convert_to_date(hash_or_value[prop_name]) : hash_or_value[prop_name] + end expected_class = expected_type.class value_class = value.class next expect_json_types_impl(expected_type, value) if is_hash?(expected_class) next expected_type.call(value) if expected_class == Proc @@ -163,31 +166,39 @@ expectations.class == Airborne::OptionalHashTypeExpectations && hash.nil? end def expect_type(expected_type, value_class, prop_name = nil) insert = prop_name.nil? ? "" : "#{prop_name} to be of type" - msg = "Expected #{insert} #{expected_type}\n, got #{value_class} instead" + msg = "Expected #{insert} #{expected_type}\n got #{value_class} instead" expect(@mapper[expected_type].include?(value_class)).to eq(true), msg end def is_hash?(expected_class) expected_class == Hash || expected_class == Airborne::OptionalHashTypeExpectations end def expect_array(value_class, prop_name, expected_type) - expect(value_class).to eq(Array), "Expected #{prop_name}\n to be of type #{expected_type}\n, got #{value_class} instead" + expect(value_class).to eq(Array), "Expected #{prop_name}\n to be of type #{expected_type}\n got #{value_class} instead" end def expect_json_impl(expectations, hash) hash = hash.to_s if expectations.class == Regexp return expect(hash).to match(expectations) if is_property?(expectations) expectations.each do |prop_name, expected_value| - actual_value = hash[prop_name] + actual_value = ensure_hash_contains_prop(prop_name, hash) {hash[prop_name]} expected_class = expected_value.class next expect_json_impl(expected_value, actual_value) if expected_class == Hash next expected_value.call(actual_value) if expected_class == Proc next expect(actual_value.to_s).to match(expected_value) if expected_class == Regexp expect(actual_value).to eq(expected_value) + end + end + + def ensure_hash_contains_prop(prop_name, hash) + begin + yield + rescue + raise ExpectationError, "Expected #{hash.class} #{hash}\nto be an object with property #{prop_name}" end end # Convert integers in `old_expectations` to proc #