File: fetch_spec.rb

package info (click to toggle)
ruby3.3 3.3.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 153,620 kB
  • sloc: ruby: 1,244,308; ansic: 836,474; yacc: 28,074; pascal: 6,748; sh: 3,913; python: 1,719; cpp: 1,158; makefile: 742; asm: 712; javascript: 394; lisp: 97; perl: 62; awk: 36; sed: 23; xml: 4
file content (55 lines) | stat: -rw-r--r-- 1,833 bytes parent folder | download | duplicates (7)
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
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

describe "Array#fetch" do
  it "returns the element at the passed index" do
    [1, 2, 3].fetch(1).should == 2
    [nil].fetch(0).should == nil
  end

  it "counts negative indices backwards from end" do
    [1, 2, 3, 4].fetch(-1).should == 4
  end

  it "raises an IndexError if there is no element at index" do
    -> { [1, 2, 3].fetch(3) }.should raise_error(IndexError)
    -> { [1, 2, 3].fetch(-4) }.should raise_error(IndexError)
    -> { [].fetch(0) }.should raise_error(IndexError)
  end

  it "returns default if there is no element at index if passed a default value" do
    [1, 2, 3].fetch(5, :not_found).should == :not_found
    [1, 2, 3].fetch(5, nil).should == nil
    [1, 2, 3].fetch(-4, :not_found).should == :not_found
    [nil].fetch(0, :not_found).should == nil
  end

  it "returns the value of block if there is no element at index if passed a block" do
    [1, 2, 3].fetch(9) { |i| i * i }.should == 81
    [1, 2, 3].fetch(-9) { |i| i * i }.should == 81
  end

  it "passes the original index argument object to the block, not the converted Integer" do
    o = mock('5')
    def o.to_int(); 5; end

    [1, 2, 3].fetch(o) { |i| i }.should equal(o)
  end

  it "gives precedence to the default block over the default argument" do
    -> {
      @result = [1, 2, 3].fetch(9, :foo) { |i| i * i }
    }.should complain(/block supersedes default value argument/)
    @result.should == 81
  end

  it "tries to convert the passed argument to an Integer using #to_int" do
    obj = mock('to_int')
    obj.should_receive(:to_int).and_return(2)
    ["a", "b", "c"].fetch(obj).should == "c"
  end

  it "raises a TypeError when the passed argument can't be coerced to Integer" do
    -> { [].fetch("cat") }.should raise_error(TypeError)
  end
end