Skip to content

Instantly share code, notes, and snippets.

@rwz
Last active January 2, 2016 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwz/8284868 to your computer and use it in GitHub Desktop.
Save rwz/8284868 to your computer and use it in GitHub Desktop.
An interesting Ruby problem
class MyHash < Hash
undef_method :fetch
def fetch(*)
# your code goes here
end
end
require "rspec/autorun"
describe MyHash do
subject{ MyHash[:key, :value] }
context "#fetch" do
it "returns value when key is present" do
expect(subject.fetch(:key)).to eq(:value)
end
it "returns value when key is present regardless other arguments" do
expect(subject.fetch(:key, :lol){ :wut }).to eq(:value)
end
it "raises ArgumentError when too many arguments are provided" do
expect{ subject.fetch(:lol, :wut, :fizz) }.to raise_error(ArgumentError)
end
it "throws an error when key is not present" do
expect{ subject.fetch(:lol) }.to raise_error(KeyError)
end
it "returns a provided value if key is not present" do
expect(subject.fetch(:lol, :another_value)).to eq(:another_value)
end
it "returns nil when it's provided as a value" do
expect(subject.fetch(:lol, nil)).to eq(nil)
end
it "executes block when key is not present" do
expect(subject.fetch(:lol){ :another_value }).to eq(:another_value)
end
it "executes block if both block and default value are provided" do
expect(subject.fetch(:lol, :wut){ :another_value }).to eq(:another_value)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment