File: fetch_spec.rb

package info (click to toggle)
ruby-hamster 3.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,932 kB
  • sloc: ruby: 16,915; makefile: 4
file content (58 lines) | stat: -rw-r--r-- 1,810 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require "spec_helper"
require "hamster/hash"

describe Hamster::Hash do
  describe "#fetch" do
    context "with no default provided" do
      context "when the key exists" do
        it "returns the value associated with the key" do
          H["A" => "aye"].fetch("A").should == "aye"
        end
      end

      context "when the key does not exist" do
        it "raises a KeyError" do
          -> { H["A" => "aye"].fetch("B") }.should raise_error(KeyError)
        end
      end
    end

    context "with a default value" do
      context "when the key exists" do
        it "returns the value associated with the key" do
          H["A" => "aye"].fetch("A", "default").should == "aye"
        end
      end

      context "when the key does not exist" do
        it "returns the default value" do
          H["A" => "aye"].fetch("B", "default").should == "default"
        end
      end
    end

    context "with a default block" do
      context "when the key exists" do
        it "returns the value associated with the key" do
          H["A" => "aye"].fetch("A") { "default".upcase }.should == "aye"
        end
      end

      context "when the key does not exist" do
        it "invokes the default block with the missing key as paramter" do
          H["A" => "aye"].fetch("B") { |key| key.should == "B" }
          H["A" => "aye"].fetch("B") { "default".upcase }.should == "DEFAULT"
        end
      end
    end

    it "gives precedence to default block over default argument if passed both" do
      H["A" => "aye"].fetch("B", 'one') { 'two' }.should == 'two'
    end

    it "raises an ArgumentError when not passed one or 2 arguments" do
      -> { H.empty.fetch }.should raise_error(ArgumentError)
      -> { H.empty.fetch(1, 2, 3) }.should raise_error(ArgumentError)
    end
  end
end