summaryrefslogtreecommitdiff
path: root/spec/ruby/language/match_spec.rb
blob: ebf677cabc32bf4365ed359dc49d91cf9b5e9d99 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require_relative '../spec_helper'
require_relative 'fixtures/match_operators'

describe "The !~ operator" do
  before :each do
    @obj = OperatorImplementor.new
  end

  it "evaluates as a call to !~" do
    expected = "hello world"

    opval = (@obj !~ expected)
    methodval = @obj.send(:"!~", expected)

    opval.should == expected
    methodval.should == expected
  end
end

describe "The =~ operator" do
  before :each do
    @impl = OperatorImplementor.new
  end

  it "calls the =~ method" do
    expected = "hello world"

    opval = (@obj =~ expected)
    methodval = @obj.send(:"=~", expected)

    opval.should == expected
    methodval.should == expected
  end
end

describe "The =~ operator with named captures" do
  before :each do
    @regexp = /(?<matched>foo)(?<unmatched>bar)?/
    @string = "foofoo"
  end

  describe "on syntax of /regexp/ =~ string_variable" do
    it "sets local variables by the captured pairs" do
      /(?<matched>foo)(?<unmatched>bar)?/ =~ @string
      local_variables.should == [:matched, :unmatched]
      matched.should == "foo"
      unmatched.should == nil
    end
  end

  describe "on syntax of 'string_literal' =~ /regexp/" do
    it "does not set local variables" do
      'string literal' =~ /(?<matched>str)(?<unmatched>lit)?/
      local_variables.should == []
    end
  end

  describe "on syntax of string_variable =~ /regexp/" do
    it "does not set local variables" do
      @string =~ /(?<matched>foo)(?<unmatched>bar)?/
      local_variables.should == []
    end
  end

  describe "on syntax of regexp_variable =~ string_variable" do
    it "does not set local variables" do
      @regexp =~ @string
      local_variables.should == []
    end
  end

  describe "on the method calling" do
    it "does not set local variables" do
      @regexp.=~(@string)
      local_variables.should == []

      @regexp.send :=~, @string
      local_variables.should == []
    end
  end
end