Skip to content

Commit

Permalink
Raise an InvalidKeyErrors on substring of valid keys
Browse files Browse the repository at this point in the history
Fixes dry-rb#705

I'm not completely sure of the fix, but it's probably good enough
as a starting point
  • Loading branch information
Mathieu Le Tiec committed Mar 3, 2022
1 parent 301e1fd commit 1284a2d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/dry/validation/contract/class_interface.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ def ensure_valid_keys(*keys)
key_paths = key_paths(keys)

invalid_keys = key_paths.map { |(key, path)|
unless valid_paths.any? { |vp| vp.include?(path) || vp.include?("#{path}[]") }
unless valid_paths.any? { |vp|
vp == path || vp.include?("#{path}.") || vp.include?("#{path}[]")
}
key
end
}.compact.uniq
Expand Down
34 changes: 34 additions & 0 deletions spec/integration/contract/class_interface/rule_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,40 @@ def self.name
end
end

context "when keys are substring of valid keys" do
it "raises error with a list of symbol keys" do
expect { contract_class.rule(:details, :addres) }
.to raise_error(
Dry::Validation::InvalidKeysError,
"TestContract.rule specifies keys that are not defined by the schema: [:addres]"
)
end

it "raises error with a hash path" do
expect { contract_class.rule(details: :addres) }
.to raise_error(
Dry::Validation::InvalidKeysError,
"TestContract.rule specifies keys that are not defined by the schema: [{:details=>:addres}]"
)
end

it "raises error with a dot notation" do
expect { contract_class.rule("details.addres") }
.to raise_error(
Dry::Validation::InvalidKeysError,
'TestContract.rule specifies keys that are not defined by the schema: ["details.addres"]'
)
end

it "raises error with a hash path with multiple nested keys" do
expect { contract_class.rule(details: %i[addres]) }
.to raise_error(
Dry::Validation::InvalidKeysError,
"TestContract.rule specifies keys that are not defined by the schema: [{:details=>[:addres]}]"
)
end
end

describe "abstract contract" do
let(:abstract_contract) do
Class.new(Dry::Validation::Contract) do
Expand Down

0 comments on commit 1284a2d

Please sign in to comment.