forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 2
/
cli_spec.rb
2207 lines (1890 loc) · 71.6 KB
/
cli_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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require 'timeout'
RSpec.describe RuboCop::CLI, :isolated_environment do
subject(:cli) { described_class.new }
include_context 'cli spec behavior'
context 'when interrupted' do
it 'returns 130' do
allow_any_instance_of(RuboCop::Runner).to receive(:aborting?).and_return(true)
create_empty_file('example.rb')
expect(cli.run(['example.rb'])).to eq(130)
end
end
context 'when given a file/directory that is not under the current dir' do
shared_examples 'checks Rakefile' do
it 'checks a Rakefile but Style/FileName does not report' do
create_file('Rakefile', <<~RUBY)
# frozen_string_literal: true
x = 1
RUBY
create_empty_file('other/empty')
Dir.chdir('other') { expect(cli.run(['--format', 'simple', checked_path])).to eq(1) }
expect($stdout.string).to eq(<<~RESULT)
== #{abs('Rakefile')} ==
W: 3: 1: Lint/UselessAssignment: Useless assignment to variable - x.
1 file inspected, 1 offense detected
RESULT
end
end
context 'and the directory is absolute' do
let(:checked_path) { abs('..') }
include_examples 'checks Rakefile'
end
context 'and the directory is relative' do
let(:checked_path) { '..' }
include_examples 'checks Rakefile'
end
context 'and the Rakefile path is absolute' do
let(:checked_path) { abs('../Rakefile') }
include_examples 'checks Rakefile'
end
context 'and the Rakefile path is relative' do
let(:checked_path) { '../Rakefile' }
include_examples 'checks Rakefile'
end
end
context 'when lines end with CR+LF' do
it 'reports an offense' do
create_file('example.rb', <<~RUBY)
x = 0\r
puts x\r
RUBY
# Make Style/EndOfLine give same output regardless of platform.
create_file('.rubocop.yml', <<~YAML)
EndOfLine:
EnforcedStyle: lf
YAML
result = cli.run(['--format', 'simple', 'example.rb'])
expect(result).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 1: Layout/EndOfLine: Carriage return character detected.
C: 1: 1: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
1 file inspected, 2 offenses detected, 1 offense autocorrectable
RESULT
expect($stderr.string).to eq(<<~RESULT)
#{abs('.rubocop.yml')}: Warning: no department given for EndOfLine.
RESULT
end
end
context 'when checking a correct file' do
it 'returns 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect($stdout.string)
.to eq(<<~RESULT)
1 file inspected, no offenses detected
RESULT
end
context 'when super is used with a block' do
it 'still returns 0' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
# this is a class
class Thing
def super_with_block
super { |response| }
end
def and_with_args
super(arg1, arg2) { |response| }
end
end
RUBY
create_file('.rubocop.yml', <<~YAML)
Lint/UnusedBlockArgument:
IgnoreEmptyBlocks: true
YAML
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(0)
expect($stdout.string)
.to eq(<<~RESULT)
1 file inspected, no offenses detected
RESULT
end
end
end
it 'checks a given file with faults and returns 1' do
create_file('example.rb', ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x'])
expect(cli.run(['--format', 'simple', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq <<~RESULT
== example.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
it 'registers an offense for a syntax error' do
create_file('example.rb', ['class Test', 'en'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq ''
expect($stdout.string)
.to eq(["#{abs('example.rb')}:3:1: E: Lint/Syntax: unexpected " \
'token $end (Using Ruby 2.6 parser; configure using ' \
'`TargetRubyVersion` parameter, under `AllCops`)',
''].join("\n"))
end
it 'registers an offense for Parser warnings' do
create_file('example.rb', [
'# frozen_string_literal: true',
'',
'puts *test',
'if a then b else c end'
])
aggregate_failures('CLI output') do
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(["#{abs('example.rb')}:3:6: W: [Correctable] Lint/AmbiguousOperator: " \
'Ambiguous splat operator. Parenthesize the method arguments ' \
"if it's surely a splat operator, or add a whitespace to the " \
'right of the `*` if it should be a multiplication.',
"#{abs('example.rb')}:4:1: C: [Correctable] Style/OneLineConditional: " \
'Favor the ternary operator (`?:`) or multi-line constructs over ' \
'single-line `if/then/else/end` constructs.',
''].join("\n"))
end
end
it 'can process a file with an invalid UTF-8 byte sequence' do
create_file('example.rb', ["# #{'f9'.hex.chr}#{'29'.hex.chr}"])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq ''
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:1:1: F: Lint/Syntax: Invalid byte sequence in utf-8.
RESULT
end
context 'when errors are raised while processing files due to bugs' do
let(:errors) { ['An error occurred while Encoding cop was inspecting file.rb.'] }
before { allow_any_instance_of(RuboCop::Runner).to receive(:errors).and_return(errors) }
it 'displays an error message to stderr' do
cli.run([])
expect($stderr.string).to include('1 error occurred:').and include(errors.first)
end
end
if RUBY_ENGINE == 'ruby' && !RuboCop::Platform.windows?
# NOTE: It has been tested for parallelism with `--debug` option.
# In other words, even if no option is specified, it will be parallelized by default.
describe 'when parallel static by default' do
context 'when specifying `--debug` option only`' do
it 'fails with an error message' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
end
end
# NOTE: Cannot be autocorrected with `parallel`.
context 'when specifying `--debug` and `-a` options`' do
it 'fails with an error message' do
create_file('example1.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
expect(cli.run(['--debug', '-a'])).to eq(0)
expect($stdout.string).not_to include('Use parallel by default.')
end
end
context 'when setting `UseCache: true`' do
it 'fails with an error message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
UseCache: true
YAML
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).to include('Use parallel by default.')
end
end
context 'when setting `UseCache: false`' do
it 'fails with an error message' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
puts 'hello'
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
UseCache: false
YAML
expect(cli.run(['--debug'])).to eq(0)
expect($stdout.string).not_to include('Use parallel by default.')
end
end
end
context 'when a directory is named `*`' do
before do
FileUtils.mkdir('*')
end
after do
FileUtils.rmdir('*')
end
it 'does not crash' do
expect(cli.run([])).to eq(0)
end
end
end
describe 'rubocop:disable comment' do
it 'can disable all cops in a code section' do
src = ['# rubocop:disable all',
'#' * 130,
'x(123456)',
'y("123")',
'def func',
' # rubocop: enable Layout/LineLength,Style/StringLiterals',
" #{'#' * 130}",
' x(123456)',
' y("123")',
'end']
create_file('example.rb', src)
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
# all cops were disabled, then 2 were enabled again, so we
# should get 2 offenses reported.
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:7:121: C: Layout/LineLength: Line is too long. [132/120]
#{abs('example.rb')}:9:5: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
RESULT
end
describe 'Specify `--init` option to `rubocop` command' do
context 'when .rubocop.yml does not exist' do
it 'generate a .rubocop.yml file' do
expect(cli.run(['--init'])).to eq(0)
expect($stdout.string).to start_with('Writing new .rubocop.yml to')
expect(File.read('.rubocop.yml')).to eq(<<~YAML)
# The behavior of RuboCop can be controlled via the .rubocop.yml
# configuration file. It makes it possible to enable/disable
# certain cops (checks) and to alter their behavior if they accept
# any parameters. The file can be placed either in your home
# directory or in some project directory.
#
# RuboCop will start looking for the configuration file in the directory
# where the inspected file is and continue its way up to the root directory.
#
# See https://docs.rubocop.org/rubocop/configuration
YAML
end
end
context 'when .rubocop.yml already exists' do
it 'fails with an error message' do
create_empty_file('.rubocop.yml')
expect(cli.run(['--init'])).to eq(2)
expect($stderr.string).to start_with('.rubocop.yml already exists at')
end
end
end
context 'when --autocorrect-all is given' do
it 'does not trigger RedundantCopDisableDirective due to lines moving around' do
src = ['a = 1 # rubocop:disable Lint/UselessAssignment']
create_file('example.rb', src)
create_file('.rubocop.yml', <<~YAML)
Style/FrozenStringLiteralComment:
Enabled: true
EnforcedStyle: always
Layout/EmptyLineAfterMagicComment:
Enabled: false
YAML
expect(cli.run(['--format', 'offenses', '-A', 'example.rb'])).to eq(0)
expect($stdout.string).to eq(<<~RESULT)
1 Style/FrozenStringLiteralComment
--
1 Total
RESULT
expect(File.read('example.rb'))
.to eq(<<~RUBY)
# frozen_string_literal: true
a = 1 # rubocop:disable Lint/UselessAssignment
RUBY
end
end
it 'can disable selected cops in a code section' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'# rubocop:disable Style/LineLength,' \
'Style/NumericLiterals,Style/StringLiterals',
'#' * 130,
'x(123456)',
'y("123")',
'def func',
' # rubocop: enable Layout/LineLength, ' \
'Style/StringLiterals',
" #{'#' * 130}",
' x(123456)',
' y("123")',
' # rubocop: enable Style/NumericLiterals',
'end'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string)
.to eq(['example.rb: Style/LineLength has the wrong ' \
'namespace - should be Layout',
''].join("\n"))
# 2 real cops were disabled, and 1 that was incorrect
# 2 real cops was enabled, but only 1 had been disabled correctly
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:8:21: W: [Correctable] Lint/RedundantCopEnableDirective: Unnecessary enabling of Layout/LineLength.
#{abs('example.rb')}:9:121: C: Layout/LineLength: Line is too long. [132/120]
#{abs('example.rb')}:11:5: C: [Correctable] Style/StringLiterals: Prefer single-quoted strings when you don't need string interpolation or special symbols.
RESULT
end
it 'can disable all cops on a single line' do
create_file('example.rb', 'y("123", 123456) # rubocop:disable all')
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(0)
expect($stdout.string.empty?).to be(true)
end
it 'can disable selected cops on a single line' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
"#{'a' * 130} # rubocop:disable Layout/LineLength",
'#' * 130,
'y("123", 123456) # rubocop:disable Style/StringLiterals,' \
'Style/NumericLiterals'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:4:121: C: Layout/LineLength: Line is too long. [130/120]
RESULT
end
context 'without using namespace' do
it 'can disable selected cops on a single line but prints a warning' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
"#{'a' * 130} # rubocop:disable LineLength",
'#' * 130,
'y("123") # rubocop:disable StringLiterals'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq(<<~OUTPUT)
#{abs('example.rb')}: Warning: no department given for LineLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
#{abs('example.rb')}: Warning: no department given for StringLiterals. Run `rubocop -a --only Migration/DepartmentName` to fix.
OUTPUT
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:3:150: C: [Correctable] Migration/DepartmentName: Department name is missing.
#{abs('example.rb')}:4:121: C: Layout/LineLength: Line is too long. [130/120]
#{abs('example.rb')}:5:28: C: [Correctable] Migration/DepartmentName: Department name is missing.
RESULT
end
end
context 'when not necessary' do
it 'causes an offense to be reported' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'#' * 130,
'# rubocop:disable all',
"#{'a' * 10} # rubocop:disable Layout/LineLength,Metrics/ClassLength",
'y(123) # rubocop:disable all',
'# rubocop:enable all'])
expect(cli.run(['--format', 'emacs', 'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~RESULT)
#{abs('example.rb')}:3:121: C: Layout/LineLength: Line is too long. [130/120]
#{abs('example.rb')}:4:1: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of all cops.
#{abs('example.rb')}:5:12: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of `Layout/LineLength`, `Metrics/ClassLength`.
#{abs('example.rb')}:6:8: W: [Correctable] Lint/RedundantCopDisableDirective: Unnecessary disabling of all cops.
RESULT
end
context 'and there are no other offenses' do
it 'exits with error code' do
create_file('example.rb', "#{'a' * 10} # rubocop:disable LineLength")
expect(cli.run(['example.rb'])).to eq(1)
end
end
context 'when using `rubocop:disable` line comment for `Lint/EmptyBlock`' do
it 'does not register an offense for `Lint/RedundantCopDisableDirective`' do
create_file('.rubocop.yml', <<~YAML)
Lint/EmptyBlock:
Enabled: true
Lint/RedundantCopDisableDirective:
Enabled: true
YAML
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
assert_equal nil, combinator {}.call # rubocop:disable Lint/EmptyBlock'
RUBY
expect(cli.run(['example.rb'])).to eq(0)
expect($stdout.string).to include('1 file inspected, no offenses detected')
end
end
shared_examples 'RedundantCopDisableDirective not run' do |state, config|
context "and RedundantCopDisableDirective is #{state}" do
it 'does not report RedundantCopDisableDirective offenses' do
create_file('example.rb',
['# frozen_string_literal: true',
'',
'#' * 130,
'# rubocop:disable all',
"#{'a' * 10} # rubocop:disable LineLength,ClassLength",
'y(123) # rubocop:disable all'])
create_file('.rubocop.yml', config)
expect(cli.run(['--format', 'emacs'])).to eq(1)
expect($stderr.string).to eq(<<~OUTPUT)
#{abs('example.rb')}: Warning: no department given for LineLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
#{abs('example.rb')}: Warning: no department given for ClassLength. Run `rubocop -a --only Migration/DepartmentName` to fix.
OUTPUT
expect($stdout.string)
.to eq(<<~RESULT)
#{abs('example.rb')}:3:121: C: Layout/LineLength: Line is too long. [130/120]
RESULT
end
end
end
include_examples 'RedundantCopDisableDirective not run',
'individually disabled', <<~YAML
Lint/RedundantCopDisableDirective:
Enabled: false
YAML
include_examples 'RedundantCopDisableDirective not run',
'individually excluded', <<~YAML
Lint/RedundantCopDisableDirective:
Exclude:
- example.rb
YAML
include_examples 'RedundantCopDisableDirective not run',
'disabled through department', <<~YAML
Lint:
Enabled: false
YAML
end
end
it 'finds a file with no .rb extension but has a shebang line' do
allow_any_instance_of(File::Stat).to receive(:executable?).and_return(true)
create_file('example', ['#!/usr/bin/env ruby', 'x = 0', 'puts x'])
create_file('.rubocop.yml', <<~YAML)
Style/FrozenStringLiteralComment:
Enabled: false
YAML
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
it 'does not register any offenses for an empty file' do
create_empty_file('example.rb')
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
describe 'style guide only usage' do
context 'via the cli option' do
describe '--only-guide-cops' do
it 'skips cops that have no link to a style guide' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(0)
end
it 'runs cops for rules that link to a style guide' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Enabled: true
StyleGuide: "http://an.example/url"
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 3: Layout/LineLength: Line is too long. [5/2]
1 file inspected, 1 offense detected
RESULT
end
it 'overrides configuration of AllCops/StyleGuideCopsOnly' do
create_file('example.rb', 'raise')
create_file('.rubocop.yml', <<~YAML)
AllCops:
StyleGuideCopsOnly: false
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
YAML
expect(cli.run(['--format', 'simple', '--only-guide-cops', 'example.rb'])).to eq(0)
end
end
end
context 'via the config' do
before do
create_file('example.rb', <<~RUBY)
if foo and bar
do_something
end
RUBY
create_file('.rubocop.yml', <<~YAML)
AllCops:
StyleGuideCopsOnly: #{guide_cops_only}
DisabledByDefault: #{disabled_by_default}
Layout/LineLength:
Enabled: true
StyleGuide: ~
Max: 2
Style/FrozenStringLiteralComment:
Enabled: false
YAML
end
describe 'AllCops/StyleGuideCopsOnly' do
let(:disabled_by_default) { 'false' }
context 'when it is true' do
let(:guide_cops_only) { 'true' }
it 'skips cops that have no link to a style guide' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
1 Style/AndOr
--
1 Total
RESULT
end
end
context 'when it is false' do
let(:guide_cops_only) { 'false' }
it 'runs cops for rules regardless of any link to the style guide' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength
1 Style/AndOr
--
4 Total
RESULT
end
end
end
describe 'AllCops/DisabledByDefault' do
let(:guide_cops_only) { 'false' }
context 'when it is true' do
let(:disabled_by_default) { 'true' }
it 'runs only the cop configured in .rubocop.yml' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength
--
3 Total
RESULT
end
end
context 'when it is false' do
let(:disabled_by_default) { 'false' }
it 'runs all cops that are enabled in default configuration' do
expect(cli.run(['--format', 'offenses', 'example.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
3 Layout/LineLength
1 Style/AndOr
--
4 Total
RESULT
end
end
end
end
end
describe 'cops can exclude files based on config' do
it 'ignores excluded files' do
create_file('example.rb', 'x = 0')
create_file('regexp.rb', 'x = 0')
create_file('exclude_glob.rb', ['#!/usr/bin/env ruby', 'x = 0'])
create_file('dir/thing.rb', 'x = 0')
create_file('.rubocop.yml', <<~'YAML')
Lint/UselessAssignment:
Exclude:
- example.rb
- !ruby/regexp /regexp.rb\z/
- "exclude_*"
- "dir/*"
Style/FrozenStringLiteralComment:
Enabled: false
YAML
allow_any_instance_of(File::Stat).to receive(:executable?).and_return(true)
expect(cli.run(%w[--format simple])).to eq(0)
expect($stdout.string).to eq(['', '4 files inspected, no offenses detected', ''].join("\n"))
end
end
describe 'configuration from file' do
before { RuboCop::ConfigLoader.default_configuration = nil }
context 'when a value in a hash is overridden with nil' do
it 'acts as if the key/value pair was removed' do
create_file('.rubocop.yml', <<~YAML)
Style/InverseMethods:
InverseMethods:
:even?: ~
Style/CollectionMethods:
Enabled: true
PreferredMethods:
collect: ~
Style/FrozenStringLiteralComment:
Enabled: false
YAML
create_file('example.rb', 'array.collect { |e| !e.odd? }')
expect(cli.run([])).to eq(0)
end
end
context 'when configured for indented_internal_methods style indentation' do
it 'accepts indented_internal_methods style indentation' do
create_file('.rubocop.yml', <<~YAML)
Layout/IndentationConsistency:
EnforcedStyle: indented_internal_methods
Style/FrozenStringLiteralComment:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
# A feline creature
class Cat
def meow
puts('Meow!')
end
protected
def can_we_be_friends?(another_cat)
some_logic(another_cat)
end
private
def meow_at_3am?
rand < 0.8
end
end
RUBY
result = cli.run(%w[--format simple])
expect($stderr.string).to eq('')
expect(result).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
%w[class module].each do |parent|
it "registers offense for normal indentation in #{parent}" do
create_file('.rubocop.yml', <<~YAML)
Layout/IndentationConsistency:
EnforcedStyle: indented_internal_methods
Style/FrozenStringLiteralComment:
Enabled: false
YAML
create_file('example.rb', <<~RUBY)
# A feline creature
#{parent} Cat
def meow
puts('Meow!')
end
protected
def can_we_be_friends?(another_cat)
some_logic(another_cat)
end
private
def meow_at_3am?
rand < 0.8
end
def meow_at_4am?
rand < 0.8
end
end
RUBY
result = cli.run(%w[--format simple])
expect($stderr.string).to eq('')
expect(result).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 9: 3: [Correctable] Layout/IndentationWidth: Use 2 (not 0) spaces for indented_internal_methods indentation.
C: 15: 3: [Correctable] Layout/IndentationWidth: Use 2 (not 0) spaces for indented_internal_methods indentation.
1 file inspected, 2 offenses detected, 2 offenses autocorrectable
RESULT
end
end
end
context 'when obsolete MultiSpaceAllowedForOperators param is used' do
it 'displays a warning' do
create_file('.rubocop.yml', <<~YAML)
Layout/SpaceAroundOperators:
MultiSpaceAllowedForOperators:
- "="
YAML
expect(cli.run([])).to eq(2)
expect($stderr.string).to include('obsolete parameter ' \
'`MultiSpaceAllowedForOperators` ' \
'(for `Layout/SpaceAroundOperators`)' \
' found')
end
end
context 'when MultilineMethodCallIndentation is used with aligned ' \
'style and IndentationWidth parameter' do
it 'fails with an error message' do
create_file('example.rb', 'puts 1')
create_file('.rubocop.yml', <<~YAML)
Layout/MultilineMethodCallIndentation:
EnforcedStyle: aligned
IndentationWidth: 1
YAML
expect(cli.run(['example.rb'])).to eq(2)
expect($stderr.string.strip).to eq(
'Error: The `Layout/MultilineMethodCallIndentation` cop only ' \
'accepts an `IndentationWidth` configuration parameter when ' \
'`EnforcedStyle` is `indented`.'
)
end
end
context 'when MultilineOperationIndentation is used with aligned ' \
'style and IndentationWidth parameter' do
it 'fails with an error message' do
create_file('example.rb', 'puts 1')
create_file('.rubocop.yml', <<~YAML)
Layout/MultilineOperationIndentation:
EnforcedStyle: aligned
IndentationWidth: 1
YAML
expect(cli.run(['example.rb'])).to eq(2)
expect($stderr.string.strip).to eq(
'Error: The `Layout/MultilineOperationIndentation` cop only accepts' \
' an `IndentationWidth` configuration parameter when ' \
'`EnforcedStyle` is `indented`.'
)
end
end
it 'allows the default configuration file as the -c argument' do
create_file('example.rb', <<~RUBY)
# frozen_string_literal: true
x = 0
puts x
RUBY
create_file('.rubocop.yml', [])
expect(cli.run(%w[--format simple -c .rubocop.yml])).to eq(0)
expect($stdout.string).to eq(['', '1 file inspected, no offenses detected', ''].join("\n"))
end
context 'when --force-default-config option is specified' do
shared_examples 'ignores config file' do
it 'ignores config file' do
create_file('example.rb', ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x'])
create_file('.rubocop.yml', <<~YAML)
Layout/TrailingWhitespace:
Enabled: false
YAML
expect(cli.run(args)).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
1 file inspected, 1 offense detected, 1 offense autocorrectable
RESULT
end
end
context 'when no config file specified' do
let(:args) { %w[--format simple --force-default-config] }
include_examples 'ignores config file'
end
context 'when config file specified with -c' do
let(:args) { %w[--format simple --force-default-config -c .rubocop.yml] }
include_examples 'ignores config file'
end
end
it 'displays cop names if DisplayCopNames is false' do
source = ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x']
create_file('example1.rb', source)
# DisplayCopNames: false inherited from config/default.yml
create_file('.rubocop.yml', [])
create_file('dir/example2.rb', source)
create_file('dir/.rubocop.yml', <<~YAML)
AllCops:
DisplayCopNames: false
YAML
expect(cli.run(%w[--format simple])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== dir/example2.rb ==
C: 3: 6: [Correctable] Trailing whitespace detected.
== example1.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
2 files inspected, 2 offenses detected, 2 offenses autocorrectable
RESULT
end
it 'displays style guide URLs if DisplayStyleGuide is true' do
source = ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x']
create_file('example1.rb', source)
# DisplayCopNames: false inherited from config/default.yml
create_file('.rubocop.yml', [])
create_file('dir/example2.rb', source)
create_file('dir/.rubocop.yml', <<~YAML)
AllCops:
DisplayStyleGuide: true
YAML
url = 'https://rubystyle.guide#no-trailing-whitespace'
expect(cli.run(%w[--format simple])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
== dir/example2.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected. (#{url})
== example1.rb ==
C: 3: 6: [Correctable] Layout/TrailingWhitespace: Trailing whitespace detected.
2 files inspected, 2 offenses detected, 2 offenses autocorrectable
RESULT
end
it 'uses the DefaultFormatter if another formatter is not specified' do
source = ['# frozen_string_literal: true', '', 'x = 0 ', 'puts x']
create_file('example1.rb', source)
create_file('.rubocop.yml', <<~YAML)
AllCops:
DefaultFormatter: offenses
YAML
expect(cli.run([])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
1 Layout/TrailingWhitespace
--
1 Total
RESULT
end
it 'finds included files' do
create_file('file.rb', 'x=0') # Included by default
create_file('example', 'x=0')
create_file('regexp', 'x=0')
create_file('vendor/bundle/ruby/2.6.0/gems/backports-3.6.8/.irbrc', 'x=0')
create_file('.dot1/file.rb', 'x=0') # Hidden but explicitly included
create_file('.dot2/file.rb', 'x=0') # Hidden, excluded by default
create_file('.dot3/file.rake', 'x=0') # Hidden, not included by wildcard
create_file('.rubocop.yml', <<~YAML)
AllCops:
Include:
- "**/.irbrc"
- example
- "**/*.rb"
- "**/*.rake"
- !ruby/regexp /regexp$/
- .dot1/**/*
Exclude:
- vendor/bundle/**/*
YAML
expect(cli.run(%w[--format files])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string.split($RS).sort).to eq([abs('.dot1/file.rb'),
abs('example'),
abs('file.rb'),
abs('regexp')])
end
it 'ignores excluded files' do