File: take.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 (63 lines) | stat: -rw-r--r-- 2,163 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
56
57
58
59
60
61
62
63
describe :enumerable_take, shared: true do
  before :each do
    @values = [4,3,2,1,0,-1]
    @enum = EnumerableSpecs::Numerous.new(*@values)
  end

  it "returns the first count elements if given a count" do
    @enum.send(@method, 2).should == [4, 3]
    @enum.send(@method, 4).should == [4, 3, 2, 1] # See redmine #1686 !
  end

  it "returns an empty array when passed count on an empty array" do
    empty = EnumerableSpecs::Empty.new
    empty.send(@method, 0).should == []
    empty.send(@method, 1).should == []
    empty.send(@method, 2).should == []
  end

  it "returns an empty array when passed count == 0" do
    @enum.send(@method, 0).should == []
  end

  it "returns an array containing the first element when passed count == 1" do
    @enum.send(@method, 1).should == [4]
  end

  it "raises an ArgumentError when count is negative" do
    -> { @enum.send(@method, -1) }.should raise_error(ArgumentError)
  end

  it "returns the entire array when count > length" do
    @enum.send(@method, 100).should == @values
    @enum.send(@method, 8).should == @values  # See redmine #1686 !
  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(3).at_most(:twice) # called twice, no apparent reason. See redmine #1554
    @enum.send(@method, obj).should == [4, 3, 2]
  end

  it "raises a TypeError if the passed argument is not numeric" do
    -> { @enum.send(@method, nil) }.should raise_error(TypeError)
    -> { @enum.send(@method, "a") }.should raise_error(TypeError)

    obj = mock("nonnumeric")
    -> { @enum.send(@method, obj) }.should raise_error(TypeError)
  end

  it "gathers whole arrays as elements when each yields multiple" do
    multi = EnumerableSpecs::YieldsMulti.new
    multi.send(@method, 1).should == [[1, 2]]
  end

  it "consumes only what is needed" do
    thrower = EnumerableSpecs::ThrowingEach.new
    thrower.send(@method, 0).should == []
    counter = EnumerableSpecs::EachCounter.new(1,2,3,4)
    counter.send(@method, 2).should == [1,2]
    counter.times_called.should == 1
    counter.times_yielded.should == 2
  end
end