forked from rubocop/rubocop
/
hash_conversion_spec.rb
101 lines (82 loc) · 2.39 KB
/
hash_conversion_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::HashConversion, :config do
it 'reports an offense for single-argument Hash[]' do
expect_offense(<<~RUBY)
Hash[ary]
^^^^^^^^^ Prefer ary.to_h to Hash[ary].
RUBY
expect_correction(<<~RUBY)
ary.to_h
RUBY
end
it 'reports different offense for multi-argument Hash[]' do
expect_offense(<<~RUBY)
Hash[a, b, c, d]
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[arg1, arg2, ...].
RUBY
expect_correction(<<~RUBY)
{a => b, c => d}
RUBY
end
it 'reports different offense for hash argument Hash[]' do
expect_offense(<<~RUBY)
Hash[a: b, c: d]
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[key: value, ...].
RUBY
expect_correction(<<~RUBY)
{a: b, c: d}
RUBY
end
it 'reports different offense for empty Hash[]' do
expect_offense(<<~RUBY)
Hash[]
^^^^^^ Prefer literal hash to Hash[arg1, arg2, ...].
RUBY
expect_correction(<<~RUBY)
{}
RUBY
end
it 'registers and corrects an offense when using multi-argument `Hash[]` as a method argument' do
expect_offense(<<~RUBY)
do_something Hash[a, b, c, d], arg
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[arg1, arg2, ...].
RUBY
expect_correction(<<~RUBY)
do_something({a => b, c => d}, arg)
RUBY
end
it 'does not try to correct multi-argument Hash with odd number of arguments' do
expect_offense(<<~RUBY)
Hash[a, b, c]
^^^^^^^^^^^^^ Prefer literal hash to Hash[arg1, arg2, ...].
RUBY
expect_no_corrections
end
it 'wraps complex statements in parens if needed' do
expect_offense(<<~RUBY)
Hash[a.foo :bar]
^^^^^^^^^^^^^^^^ Prefer ary.to_h to Hash[ary].
RUBY
expect_correction(<<~RUBY)
(a.foo :bar).to_h
RUBY
end
context 'AllowSplatArgument: true' do
let(:cop_config) { { 'AllowSplatArgument' => true } }
it 'does not register an offense for unpacked array' do
expect_no_offenses(<<~RUBY)
Hash[*ary]
RUBY
end
end
context 'AllowSplatArgument: false' do
let(:cop_config) { { 'AllowSplatArgument' => false } }
it 'reports uncorrectable offense for unpacked array' do
expect_offense(<<~RUBY)
Hash[*ary]
^^^^^^^^^^ Prefer array_of_pairs.to_h to Hash[*array].
RUBY
expect_no_corrections
end
end
end