Created
June 15, 2014 17:43
-
-
Save tamouse/4aa7226c71ced843ac3f to your computer and use it in GitHub Desktop.
A small sample of checking for extra or missing option hash parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CheckOptionsParameters | |
attr_accessor :options, :options_keys, :valid_options | |
def initialize(options, valid) | |
self.options = options.nil? ? {} : Hash(options.dup) | |
self.options_keys = @options.keys | |
self.valid_options = valid.nil? ? [] : Array(valid.dup) | |
end | |
def validate | |
missing == [] && extras == [] | |
end | |
def missing | |
valid_options - options_keys | |
end | |
def extras | |
options_keys - valid_options | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "spec_helper" | |
describe CheckOptionsParameters do | |
it "responds to :new" do | |
expect(CheckOptionsParameters).to respond_to :new | |
end | |
it "validates equal sets" do | |
expect(CheckOptionsParameters.new({a: "first", b: "second", c: "third"}, %i[a b c]).validate).to be_true | |
end | |
it "invalidates missing parameters" do | |
expect(CheckOptionsParameters.new({a: "first"}, %i[a b c]).validate).to be_false | |
end | |
it "invalidates extra parameters" do | |
expect(CheckOptionsParameters.new({a: "first", b: "second"}, %i[a]).validate).to be_false | |
end | |
it "handles nil valid keys" do | |
expect(CheckOptionsParameters.new({}, nil).validate).to be_true | |
end | |
it "handles nil options" do | |
expect(CheckOptionsParameters.new(nil, []).validate).to be_true | |
end | |
it "handles nil options and valid keys" do | |
expect(CheckOptionsParameters.new(nil, nil).validate).to be_true | |
end | |
it "deals with non-hash options" do | |
expect{CheckOptionsParameters.new("hi", nil).validate}.to raise_error(TypeError, %r{can\'t convert String into Hash}) | |
end | |
it "deals with non-array valid keys" do | |
expect(CheckOptionsParameters.new({}, "hi").validate).to be_false | |
end | |
it "shows missing options" do | |
expect(CheckOptionsParameters.new({a: "first"}, %i[a b c]).missing).to eq(%i[b c]) | |
end | |
it "shows extra options" do | |
expect(CheckOptionsParameters.new({a: "first", b: "second", xyz: "extra"}, %i[a b c]).extras).to eq(%i[xyz]) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment