1describe :enumerable_take, shared: true do 2 before :each do 3 @values = [4,3,2,1,0,-1] 4 @enum = EnumerableSpecs::Numerous.new(*@values) 5 end 6 7 it "returns the first count elements if given a count" do 8 @enum.send(@method, 2).should == [4, 3] 9 @enum.send(@method, 4).should == [4, 3, 2, 1] # See redmine #1686 ! 10 end 11 12 it "returns an empty array when passed count on an empty array" do 13 empty = EnumerableSpecs::Empty.new 14 empty.send(@method, 0).should == [] 15 empty.send(@method, 1).should == [] 16 empty.send(@method, 2).should == [] 17 end 18 19 it "returns an empty array when passed count == 0" do 20 @enum.send(@method, 0).should == [] 21 end 22 23 it "returns an array containing the first element when passed count == 1" do 24 @enum.send(@method, 1).should == [4] 25 end 26 27 it "raises an ArgumentError when count is negative" do 28 lambda { @enum.send(@method, -1) }.should raise_error(ArgumentError) 29 end 30 31 it "returns the entire array when count > length" do 32 @enum.send(@method, 100).should == @values 33 @enum.send(@method, 8).should == @values # See redmine #1686 ! 34 end 35 36 it "tries to convert the passed argument to an Integer using #to_int" do 37 obj = mock('to_int') 38 obj.should_receive(:to_int).and_return(3).at_most(:twice) # called twice, no apparent reason. See redmine #1554 39 @enum.send(@method, obj).should == [4, 3, 2] 40 end 41 42 it "raises a TypeError if the passed argument is not numeric" do 43 lambda { @enum.send(@method, nil) }.should raise_error(TypeError) 44 lambda { @enum.send(@method, "a") }.should raise_error(TypeError) 45 46 obj = mock("nonnumeric") 47 lambda { @enum.send(@method, obj) }.should raise_error(TypeError) 48 end 49 50 it "gathers whole arrays as elements when each yields multiple" do 51 multi = EnumerableSpecs::YieldsMulti.new 52 multi.send(@method, 1).should == [[1, 2]] 53 end 54 55 it "consumes only what is needed" do 56 thrower = EnumerableSpecs::ThrowingEach.new 57 thrower.send(@method, 0).should == [] 58 counter = EnumerableSpecs::EachCounter.new(1,2,3,4) 59 counter.send(@method, 2).should == [1,2] 60 counter.times_called.should == 1 61 counter.times_yielded.should == 2 62 end 63end 64