Welcome! Please see the About page for a little more info on how this works.

0 votes
in Spec by
recategorized by

My understanding is that spec/keys works for validating specific keys in a hash-map. However, I need it to also reject a hash-map that contains keys that are not in :req and :opt.

For a contrived example, imagine I have a definition of a person as an edn:

{:name "John"
:age 25}

The spec could be:

(spec/def ::name string?)
(spec/def ::age int?)
(spec/def ::person (spec/keys :req-un [::name ::age]))

The above definition would conform to this ::person spec.

However, let's say that, due to a confusion by a developer, another key unrelated to a Person's definition was added, and the hash-map is now:

{:name "John"
:age 25
:voltage 220}

That would still conform to the spec. But I want it to fail!

Is there a simple way to make spec/keys reject a hash-map that has keys that are neither req nor opt?

1 Answer

+1 vote
selected by
Best answer

With spec 1, there isn't an easy way to do this. One workaround is to s/and a function that checks that the key set is a subset of the req/opt keys.

In spec 2, there is a new "closed spec checking" option that can be used during validation (importantly, it's an option at checking time, not part of the spec).