Skip to content
This repository has been archived by the owner on Feb 9, 2022. It is now read-only.

Commit

Permalink
Only raise missing key errors when strict checking
Browse files Browse the repository at this point in the history
This is to remain backwards compatible
  • Loading branch information
jfoley committed Nov 27, 2013
1 parent e9d64c4 commit e3bbd27
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
11 changes: 7 additions & 4 deletions lib/membrane/schemas/record.rb
Expand Up @@ -12,9 +12,10 @@ class Membrane::Schemas::Record < Membrane::Schemas::Base
attr_reader :schemas
attr_reader :optional_keys

def initialize(schemas, optional_keys = [])
def initialize(schemas, optional_keys = [], strict_checking = false)
@optional_keys = Set.new(optional_keys)
@schemas = schemas
@strict_checking = strict_checking
end

def validate(object)
Expand All @@ -39,9 +40,11 @@ def validate(object)
end
end

extra_keys = object.keys - schema_keys
extra_keys.each do |k|
key_errors[k] = "was not specified in the schema"
if @strict_checking
extra_keys = object.keys - schema_keys
extra_keys.each do |k|
key_errors[k] = "was not specified in the schema"
end
end

if key_errors.size > 0
Expand Down
41 changes: 30 additions & 11 deletions spec/schemas/record_spec.rb
Expand Up @@ -53,19 +53,38 @@
errors.should match(/bar/)
end

it "raises an error if there are extra keys that are not matched in the schema" do
data = {
"key" => "value",
"other_key" => 2,
}
context "when strict checking" do
it "raises an error if there are extra keys that are not matched in the schema" do
data = {
"key" => "value",
"other_key" => 2,
}

rec_schema = Membrane::Schemas::Record.new({
"key" => Membrane::Schemas::Class.new(String)
}, [], true)

expect {
rec_schema.validate(data)
}.to raise_error(/other_key .* was not specified/)
end
end

context "when not strict checking" do
it "doesnt raise an error" do
data = {
"key" => "value",
"other_key" => 2,
}

rec_schema = Membrane::Schemas::Record.new({
"key" => Membrane::Schemas::Class.new(String)
})
rec_schema = Membrane::Schemas::Record.new({
"key" => Membrane::Schemas::Class.new(String)
})

expect {
rec_schema.validate(data)
}.to raise_error(/other_key .* was not specified/)
expect {
rec_schema.validate(data)
}.to_not raise_error
end
end
end

Expand Down

0 comments on commit e3bbd27

Please sign in to comment.