forked from rubocop/rubocop-performance
/
times_map_spec.rb
78 lines (67 loc) · 2.34 KB
/
times_map_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
# frozen_string_literal: true
RSpec.describe RuboCop::Cop::Performance::TimesMap, :config do
shared_examples 'map_or_collect' do |method|
context ".times.#{method}" do
context 'with a block' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
4.times.#{method} { |i| i.to_s }
^^^^^^^^^{method}^^^^^^^^^^^^^^^ Use `Array.new(4)` with a block instead of `.times.#{method}`.
RUBY
expect_correction(<<~RUBY)
Array.new(4) { |i| i.to_s }
RUBY
end
end
context 'for non-literal receiver' do
it 'registers an offense' do
expect_offense(<<~RUBY, method: method)
n.times.#{method} { |i| i.to_s }
^^^^^^^^^{method}^^^^^^^^^^^^^^^ Use `Array.new(n)` with a block instead of `.times.#{method}` only if `n` is always 0 or more.
RUBY
expect_correction(<<~RUBY)
Array.new(n) { |i| i.to_s }
RUBY
end
end
context 'with an explicitly passed block' do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
4.times.#{method}(&method(:foo))
^^^^^^^^^{method}^^^^^^^^^^^^^^^ Use `Array.new(4)` with a block instead of `.times.#{method}`.
RUBY
expect_correction(<<~RUBY)
Array.new(4, &method(:foo))
RUBY
end
end
context 'without a block' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
4.times.#{method}
RUBY
end
end
context 'called on nothing' do
it "doesn't register an offense" do
expect_no_offenses(<<~RUBY)
times.#{method} { |i| i.to_s }
RUBY
end
end
context 'when using numbered parameter', :ruby27 do
it 'registers an offense and corrects' do
expect_offense(<<~RUBY, method: method)
4.times.#{method} { _1.to_s }
^^^^^^^^^{method}^^^^^^^^^^^^ Use `Array.new(4)` with a block instead of `.times.#{method}`.
RUBY
expect_correction(<<~RUBY)
Array.new(4) { _1.to_s }
RUBY
end
end
end
end
it_behaves_like 'map_or_collect', 'map'
it_behaves_like 'map_or_collect', 'collect'
end