/
mixed_regexp_capture_types_spec.rb
82 lines (69 loc) · 2.29 KB
/
mixed_regexp_capture_types_spec.rb
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
82
# frozen_string_literal: true
RSpec.describe RuboCop::Cop::Lint::MixedRegexpCaptureTypes do
subject(:cop) { described_class.new(config) }
let(:config) { RuboCop::Config.new }
it 'registers an offense when both of named and numbered captures are used' do
expect_offense(<<~RUBY)
/(?<foo>bar)(baz)/
^^^^^^^^^^^^^^^^^^ Do not mix named captures and numbered captures in a Regexp literal.
RUBY
end
it 'does not register offense to a regexp with named capture only' do
expect_no_offenses(<<~RUBY)
/(?<foo>foo?<bar>bar)/
RUBY
end
it 'does not register offense to a regexp with numbered capture only' do
expect_no_offenses(<<~RUBY)
/(foo)(bar)/
RUBY
end
it 'does not register offense to a regexp with named capture and ' \
'non-capturing group' do
expect_no_offenses(<<~RUBY)
/(?<foo>bar)(?:bar)/
RUBY
end
# See https://github.com/rubocop-hq/rubocop/issues/8083
it 'does not register offense when using a Regexp cannot be processed by regexp_parser gem' do
expect_no_offenses(<<~'RUBY')
/data = ({"words":.+}}}[^}]*})/m
RUBY
end
# RuboCop does not know a value of variables that it will contain in the regexp literal.
# For example, `/(?<foo>#{var}*)` is interpreted as `/(?<foo>*)`.
# So it does not offense when variables are used in regexp literals.
context 'when containing a non-regexp literal' do
it 'does not register an offence when containing a lvar' do
expect_no_offenses(<<~'RUBY')
var = '(\d+)'
/(?<foo>#{var}*)/
RUBY
end
it 'does not register an offence when containing a ivar' do
expect_no_offenses(<<~'RUBY')
/(?<foo>#{@var}*)/
RUBY
end
it 'does not register an offence when containing a cvar' do
expect_no_offenses(<<~'RUBY')
/(?<foo>#{@@var}*)/
RUBY
end
it 'does not register an offence when containing a gvar' do
expect_no_offenses(<<~'RUBY')
/(?<foo>#{$var}*)/
RUBY
end
it 'does not register an offence when containing a method' do
expect_no_offenses(<<~'RUBY')
/(?<foo>#{do_something}*)/
RUBY
end
it 'does not register an offence when containing a constant' do
expect_no_offenses(<<~'RUBY')
/(?<foo>#{CONST}*)/
RUBY
end
end
end