From 89b9ca2427cfd4cf02564cf9cef04571d6452d50 Mon Sep 17 00:00:00 2001 From: Maciej Malecki Date: Fri, 7 Apr 2017 15:31:04 +0200 Subject: [PATCH] Fix StrictHash contract for extra keys `Contracts::StrictHash` didn't complain about extra entries in a given hash. This was because of the missing assertion for keys. Specs hadn't caught this case because `age` key had a wrong type anyway. Compare keys for contract and a given hash and return false if they are equal. --- lib/contracts/builtin_contracts.rb | 1 + spec/builtin_contracts_spec.rb | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/contracts/builtin_contracts.rb b/lib/contracts/builtin_contracts.rb index cb81c60..148e786 100644 --- a/lib/contracts/builtin_contracts.rb +++ b/lib/contracts/builtin_contracts.rb @@ -405,6 +405,7 @@ def initialize(contract_hash) def valid?(arg) return false unless arg.is_a?(Hash) + return false unless arg.keys.sort.eql?(contract_hash.keys.sort) contract_hash.all? do |key, _v| contract_hash.key?(key) && Contract.valid?(arg[key], contract_hash[key]) diff --git a/spec/builtin_contracts_spec.rb b/spec/builtin_contracts_spec.rb index be718ad..00cf495 100644 --- a/spec/builtin_contracts_spec.rb +++ b/spec/builtin_contracts_spec.rb @@ -448,7 +448,7 @@ def something(hash) context "when given an input with extra keys" do it "raises an error" do - fails { @o.strict_person(:name => "calvin", :age => "10", :soft => true) } + fails { @o.strict_person(:name => "calvin", :age => 10, :soft => true) } end end