aboutsummaryrefslogtreecommitdiff
path: root/spec/tokens_spec.cr
blob: ab43ce26efdff5a8829d403305edea1be04969dd (plain)
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
require "./spec_helper"

include Parcom

describe Tokens do
  describe ".from_string" do
    it "constructs a Tokens(Char) from a String" do
      tokens = Tokens.from_string("abcd")
      tokens.tokens.should eq("abcd".chars)
    end
  end

  describe "#initialize" do
    it "wraps an array with the contents of the given iterable" do
      set = Set{'a', 'b', 'c', 'd'}
      tokens = Tokens.new(set)
      tokens.tokens.should eq(set.to_a)

      arr = "abcd".chars
      tokens = Tokens.new(arr)
      tokens.tokens.should eq(arr)
    end
  end

  context do
    tokens_empty = Tokens.new([] of Char)
    tokens = Tokens.from_string("abcd")

    describe "#[]" do
      it "returns the token at the given index" do
        tokens[2].should eq('c')
        expect_raises(IndexError) { tokens_empty[2] }
      end

      it "returns a new Tokens similar to Array#[](Int, Int)" do
        tokens[1, 5].should eq(Tokens.new(['b', 'c', 'd']))
        expect_raises(IndexError) { tokens_empty[1, 5] }
      end

      it "returns a new Tokens similar to Array#[](Range)" do
        tokens[1..3].should eq(Tokens.new(['b', 'c', 'd']))
        expect_raises(IndexError) { tokens_empty[1..3] }
      end
    end

    describe "#[]?" do
      it "analogous to `Array#[]?`" do
        # we should only need to check the nil-returning cases
        tokens_empty[2]?.should be_nil
        tokens_empty[1, 5]?.should be_nil
        tokens_empty[1..3]?.should be_nil
      end
    end

    describe "#empty?" do
      it "exposes the `#empty?` method of the wrapped array" do
        tokens.empty?.should be_false
        tokens_empty.empty?.should be_true
      end
    end
  end
end