forked from rubocop/rubocop
/
cli_options_spec.rb
1473 lines (1300 loc) · 50.9 KB
/
cli_options_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
RSpec.describe RuboCop::CLI, :isolated_environment do
include_context 'cli spec behavior'
subject(:cli) { described_class.new }
before do
RuboCop::ConfigLoader.default_configuration = nil
end
describe '--parallel' do
if RuboCop::Platform.windows?
context 'on Windows' do
it 'prints a warning' do
cli.run ['-P']
expect($stderr.string)
.to include('Process.fork is not supported by this Ruby')
end
end
else
context 'combined with AllCops:UseCache:false' do
before do
create_file('.rubocop.yml', ['AllCops:',
' UseCache: false'])
end
it 'fails with an error message' do
cli.run %w[-P]
expect($stderr.string)
.to include('-P/--parallel uses caching to speed up execution, ' \
'so combining with AllCops: UseCache: false is not ' \
'allowed.')
end
end
context 'on Unix-like systems' do
it 'prints a message if --debug is specified' do
cli.run ['--parallel', '--debug']
expect($stdout.string).to match(/Running parallel inspection/)
end
it 'does not print a message if --debug is not specified' do
cli.run ['--parallel']
expect($stdout.string).not_to match(/Running parallel inspection/)
end
end
end
end
describe '--list-target-files' do
context 'when there are no files' do
it 'prints nothing with -L' do
cli.run ['-L']
expect($stdout.string.empty?).to be(true)
end
it 'prints nothing with --list-target-files' do
cli.run ['--list-target-files']
expect($stdout.string.empty?).to be(true)
end
end
context 'when there are some files' do
before do
create_file('show.rabl2', 'object @user => :person')
create_file('show.rabl', 'object @user => :person')
create_file('app.rb', 'puts "hello world"')
create_file('Gemfile', <<~RUBY)
source "https://rubygems.org"
gem "rubocop"
RUBY
create_file('lib/helper.rb', 'puts "helpful"')
end
context 'when there are no includes or excludes' do
it 'prints known ruby files' do
cli.run ['-L']
expect($stdout.string.split("\n")).to contain_exactly(
'app.rb', 'Gemfile', 'lib/helper.rb', 'show.rabl'
)
end
end
context 'when there is an include and exclude' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
Exclude:
- Gemfile
Include:
- "**/*.rb"
- "**/*.rabl"
- "**/*.rabl2"
YAML
end
it 'prints the included files and not the excluded ones' do
cli.run ['--list-target-files']
expect($stdout.string.split("\n")).to contain_exactly(
'app.rb', 'lib/helper.rb', 'show.rabl', 'show.rabl2'
)
end
end
end
end
describe '--version' do
it 'exits cleanly' do
expect(cli.run(['-v'])).to eq(0)
expect(cli.run(['--version'])).to eq(0)
expect($stdout.string).to eq((RuboCop::Version::STRING + "\n") * 2)
end
end
describe '--only' do
context 'when one cop is given' do
it 'runs just one cop' do
# The disable comment should not be reported as unnecessary (even if
# it is) since --only overrides configuration.
create_file('example.rb', ['# rubocop:disable LineLength',
'if x== 0 ',
"\ty",
'end'])
# IfUnlessModifier depends on the configuration of LineLength.
expect(cli.run(['--format', 'simple',
'--only', 'Style/IfUnlessModifier',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(['== example.rb ==',
'C: 2: 1: Style/IfUnlessModifier: Favor modifier if ' \
'usage when having a single-line body. Another good ' \
'alternative is the usage of control flow &&/||.',
'',
'1 file inspected, 1 offense detected',
''].join("\n"))
end
it 'exits with error if an incorrect cop name is passed' do
create_file('example.rb', ['if x== 0 ',
"\ty",
'end'])
expect(cli.run(['--only', 'Style/123'])).to eq(2)
expect($stderr.string)
.to include('Unrecognized cop or department: Style/123.')
end
it 'displays correction candidate if an incorrect cop name is given' do
create_file('example.rb', ['x'])
expect(cli.run(['--only', 'Style/BlockComment'])).to eq(2)
expect($stderr.string)
.to include('Unrecognized cop or department: Style/BlockComment.')
expect($stderr.string)
.to include('Did you mean? Style/BlockComments')
end
it 'exits with error if an empty string is given' do
create_file('example.rb', 'x')
expect(cli.run(['--only', ''])).to eq(2)
expect($stderr.string).to include('Unrecognized cop or department: .')
end
%w[Syntax Lint/Syntax].each do |name|
it "only checks syntax if #{name} is given" do
create_file('example.rb', 'x ')
expect(cli.run(['--only', name])).to eq(0)
expect($stdout.string).to include('no offenses detected')
end
end
%w[Lint/RedundantCopDisableDirective
RedundantCopDisableDirective].each do |name|
it "exits with error if cop name #{name} is passed" do
create_file('example.rb', ['if x== 0 ',
"\ty",
'end'])
expect(cli.run(['--only', 'RedundantCopDisableDirective'])).to eq(2)
expect($stderr.string)
.to include(
'Lint/RedundantCopDisableDirective cannot be used with --only.'
)
end
end
it 'accepts cop names from plugins' do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
Style/SomeCop:
Description: Something
Enabled: true
YAML
create_file('rubocop_ext.rb', <<~RUBY)
module RuboCop
module Cop
module Style
class SomeCop < Cop
end
end
end
end
RUBY
create_file('redirect.rb', '$stderr = STDOUT')
rubocop = "#{RuboCop::ConfigLoader::RUBOCOP_HOME}/exe/rubocop"
# Since we define a new cop class, we have to do this in a separate
# process. Otherwise, the extra cop will affect other specs.
output =
`ruby -I . "#{rubocop}" --require redirect.rb --only Style/SomeCop`
# Excludes a warning when new `Enabled: pending` status cop is specified
# in config/default.yml.
output_excluding_warn_for_pending_cops =
output.split("\n").last(4).join("\n") << "\n"
expect(output_excluding_warn_for_pending_cops)
.to eq(<<~RESULT)
Inspecting 2 files
..
2 files inspected, no offenses detected
RESULT
end
it 'accepts cop names from plugins with a pending cop' do
create_file('.rubocop.yml', <<~YAML)
require: rubocop_ext
Style/SomeCop:
Description: Something
Enabled: pending
YAML
create_file('rubocop_ext.rb', <<~RUBY)
module RuboCop
module Cop
module Style
class SomeCop < Cop
end
end
end
end
RUBY
create_file('redirect.rb', '$stderr = STDOUT')
rubocop = "#{RuboCop::ConfigLoader::RUBOCOP_HOME}/exe/rubocop"
# Since we define a new cop class, we have to do this in a separate
# process. Otherwise, the extra cop will affect other specs.
output =
`ruby -I . "#{rubocop}" --require redirect.rb --only Style/SomeCop`
expected_prefix = <<~PREFIX
The following cops were added to RuboCop, but are not configured. Please set Enabled to either `true` or `false` in your `.rubocop.yml` file:
PREFIX
expected_suffix = <<~SUFFIX
Inspecting 2 files
..
2 files inspected, no offenses detected
SUFFIX
expect(output).to start_with(expected_prefix)
expect(output).to end_with(expected_suffix)
remaining_range = expected_prefix.length..-(expected_suffix.length + 1)
pending_cops = output[remaining_range].split("\n")
expect(pending_cops).to include(' - Style/SomeCop')
end
context 'without using namespace' do
it 'runs just one cop' do
create_file('example.rb', ['if x== 0 ',
"\ty",
'end'])
expect(cli.run(['--format', 'simple',
'--display-cop-names',
'--only', 'IfUnlessModifier',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(['== example.rb ==',
'C: 1: 1: Style/IfUnlessModifier: Favor modifier if ' \
'usage when having a single-line body. Another good ' \
'alternative is the usage of control flow &&/||.',
'',
'1 file inspected, 1 offense detected',
''].join("\n"))
end
end
it 'enables the given cop' do
create_file('example.rb',
['x = 0 ',
# Disabling comments still apply.
'# rubocop:disable Layout/TrailingWhitespace',
'y = 1 '])
create_file('.rubocop.yml', <<~YAML)
Layout/TrailingWhitespace:
Enabled: false
YAML
expect(cli.run(['--format', 'simple',
'--only', 'Layout/TrailingWhitespace',
'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 6: Layout/TrailingWhitespace: Trailing whitespace detected.
1 file inspected, 1 offense detected
RESULT
end
end
context 'when several cops are given' do
it 'runs the given cops' do
create_file('example.rb', ['if x== 100000000000000 ',
"\ty",
'end'])
expect(cli.run(['--format', 'simple',
'--only',
'Style/IfUnlessModifier,Layout/Tab,' \
'Layout/SpaceAroundOperators',
'example.rb'])).to eq(1)
expect($stderr.string).to eq('')
expect($stdout.string).to eq(<<~RESULT)
== example.rb ==
C: 1: 1: Style/IfUnlessModifier: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.
C: 1: 5: Layout/SpaceAroundOperators: Surrounding space missing for operator ==.
C: 2: 1: Layout/Tab: Tab detected.
1 file inspected, 3 offenses detected
RESULT
end
context 'and --lint' do
it 'runs the given cops plus all enabled lint cops' do
create_file('example.rb', ['if x== 100000000000000 ',
"\ty = 3",
' end'])
create_file('.rubocop.yml', <<~YAML)
Layout/EndAlignment:
Enabled: false
YAML
expect(cli.run(['--format', 'simple',
'--only', 'Layout/Tab,Layout/SpaceAroundOperators',
'--lint',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
C: 1: 5: Layout/SpaceAroundOperators: Surrounding space missing for operator ==.
C: 2: 1: Layout/Tab: Tab detected.
W: 2: 2: Lint/UselessAssignment: Useless assignment to variable - y.
1 file inspected, 3 offenses detected
RESULT
end
end
end
context 'when a namespace is given' do
it 'runs all enabled cops in that namespace' do
create_file('example.rb', ['if x== 100000000000000 ',
' ' + '#' * 100,
"\ty",
'end'])
expect(cli.run(%w[-f offenses --only Layout example.rb])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
1 Layout/CommentIndentation
1 Layout/IndentationWidth
1 Layout/LineLength
1 Layout/SpaceAroundOperators
1 Layout/Tab
1 Layout/TrailingWhitespace
--
6 Total
RESULT
end
end
context 'when three namespaces are given' do
it 'runs all enabled cops in those namespaces' do
create_file('example.rb', ['if x== 100000000000000 ',
' # ' + '-' * 98,
"\ty",
'end'])
create_file('.rubocop.yml', <<~YAML)
Layout/SpaceAroundOperators:
Enabled: false
YAML
expect(cli.run(%w[-f o --only Metrics,Style,Layout example.rb]))
.to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
1 Layout/CommentIndentation
1 Layout/IndentationWidth
1 Layout/LineLength
1 Layout/Tab
1 Layout/TrailingWhitespace
1 Style/FrozenStringLiteralComment
1 Style/NumericLiterals
--
7 Total
RESULT
end
end
end
describe '--except' do
context 'when one name is given' do
it 'exits with error if the cop name is incorrect' do
create_file('example.rb', ['if x== 0 ',
"\ty",
'end'])
expect(cli.run(['--except', 'Style/123'])).to eq(2)
expect($stderr.string)
.to include('Unrecognized cop or department: Style/123.')
end
it 'exits with error if an empty string is given' do
create_file('example.rb', 'x')
expect(cli.run(['--except', ''])).to eq(2)
expect($stderr.string).to include('Unrecognized cop or department: .')
end
it 'displays correction candidate if an incorrect cop name is given' do
create_file('example.rb', 'x')
expect(cli.run(['--except', 'Style/BlockComment'])).to eq(2)
expect($stderr.string)
.to include('Unrecognized cop or department: Style/BlockComment.')
expect($stderr.string)
.to include('Did you mean? Style/BlockComments')
end
%w[Syntax Lint/Syntax].each do |name|
it "exits with error if #{name} is given" do
create_file('example.rb', 'x ')
expect(cli.run(['--except', name])).to eq(2)
expect($stderr.string)
.to include('Syntax checking cannot be turned off.')
end
end
end
context 'when one cop plus one namespace are given' do
it 'runs all cops except the given' do
# The disable comment should not be reported as unnecessary (even if
# it is) since --except overrides configuration.
create_file('example.rb', ['# rubocop:disable LineLength',
'if x== 0 ',
"\ty = 3",
'end'])
expect(cli.run(['--format', 'offenses',
'--except', 'Style/IfUnlessModifier,Lint',
'example.rb'])).to eq(1)
# Note: No Lint/UselessAssignment offense.
expect($stdout.string)
.to eq(<<~RESULT)
1 Layout/IndentationWidth
1 Layout/SpaceAroundOperators
1 Layout/Tab
1 Layout/TrailingWhitespace
1 Migration/DepartmentName
1 Style/FrozenStringLiteralComment
1 Style/NumericPredicate
--
7 Total
RESULT
end
end
context 'when one cop is given without namespace' do
it 'disables the given cop' do
create_file('example.rb', ['if x== 0 ',
"\ty",
'end'])
cli.run(['--format', 'offenses',
'--except', 'Style/IfUnlessModifier',
'example.rb'])
with_option = $stdout.string
$stdout = StringIO.new
cli.run(['--format', 'offenses',
'example.rb'])
without_option = $stdout.string
expect($stderr.string).to eq('')
expect(without_option.split($RS) - with_option.split($RS))
.to eq(['1 Style/IfUnlessModifier', '7 Total'])
end
end
context 'when several cops are given' do
%w[RedundantCopDisableDirective
Lint/RedundantCopDisableDirective Lint].each do |cop_name|
it "disables the given cops including #{cop_name}" do
create_file('example.rb', ['if x== 100000000000000 ',
"\ty",
'end # rubocop:disable all'])
expect(cli.run(['--format', 'offenses',
'--except',
'Style/IfUnlessModifier,Layout/Tab,' \
"Layout/SpaceAroundOperators,#{cop_name}",
'example.rb'])).to eq(1)
if cop_name == 'RedundantCopDisableDirective'
expect($stderr.string.chomp)
.to eq('--except option: Warning: no department given for ' \
'RedundantCopDisableDirective.')
end
expect($stdout.string)
.to eq(<<~RESULT)
1 Layout/IndentationWidth
1 Layout/TrailingWhitespace
1 Style/FrozenStringLiteralComment
1 Style/NumericLiterals
--
4 Total
RESULT
end
end
end
end
describe '--lint' do
it 'runs only lint cops' do
create_file('example.rb', ['if 0 ',
"\ty",
"\tz # rubocop:disable Layout/Tab",
'end'])
# IfUnlessModifier depends on the configuration of LineLength.
expect(cli.run(['--format', 'simple', '--lint',
'example.rb'])).to eq(1)
expect($stdout.string)
.to eq(<<~RESULT)
== example.rb ==
W: 1: 4: Lint/LiteralAsCondition: Literal 0 appeared as a condition.
1 file inspected, 1 offense detected
RESULT
end
end
describe '-d/--debug' do
it 'shows config files' do
create_file('example1.rb', "\tputs 0")
expect(cli.run(['--debug', 'example1.rb'])).to eq(1)
home = File.dirname(File.dirname(File.dirname(File.dirname(__FILE__))))
expect($stdout.string.lines.grep(/configuration/).map(&:chomp))
.to eq(["For #{abs('')}:" \
" configuration from #{home}/config/default.yml"])
end
it 'shows cop names' do
create_file('example1.rb', 'puts 0 ')
file = abs('example1.rb')
expect(cli.run(['--format',
'emacs',
'--debug',
'example1.rb'])).to eq(1)
expect($stdout.string.lines.to_a[-1])
.to eq("#{file}:1:7: C: Layout/TrailingWhitespace: Trailing " \
"whitespace detected.\n")
end
end
describe '-D/--display-cop-names' do
before do
create_file('example1.rb', 'puts 0 # rubocop:disable NumericLiterals ')
end
let(:file) { abs('example1.rb') }
it 'shows cop names' do
expect(cli.run(['--format', 'emacs', '--display-cop-names',
'example1.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
#{file}:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
#{file}:1:8: W: Lint/RedundantCopDisableDirective: Unnecessary disabling of `Style/NumericLiterals`.
#{file}:1:26: C: Migration/DepartmentName: Department name is missing.
#{file}:1:41: C: Layout/TrailingWhitespace: Trailing whitespace detected.
RESULT
end
context '--no-display-cop-names' do
it 'does not show cop names' do
expect(cli.run(['--format', 'emacs', '--no-display-cop-names',
'example1.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
#{file}:1:1: C: Missing frozen string literal comment.
#{file}:1:8: W: Unnecessary disabling of `Style/NumericLiterals`.
#{file}:1:26: C: Department name is missing.
#{file}:1:41: C: Trailing whitespace detected.
RESULT
end
end
context 'DisplayCopNames: false in .rubocop.yml' do
before do
create_file('.rubocop.yml', <<~YAML)
AllCops:
DisplayCopNames: false
YAML
end
it 'shows cop names' do
expect(cli.run(['--format', 'emacs', '--display-cop-names',
'example1.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
#{file}:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
#{file}:1:8: W: Lint/RedundantCopDisableDirective: Unnecessary disabling of `Style/NumericLiterals`.
#{file}:1:26: C: Migration/DepartmentName: Department name is missing.
#{file}:1:41: C: Layout/TrailingWhitespace: Trailing whitespace detected.
RESULT
end
context 'without --display-cop-names' do
it 'does not show cop names' do
expect(cli.run(['--format', 'emacs', 'example1.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
#{file}:1:1: C: Missing frozen string literal comment.
#{file}:1:8: W: Unnecessary disabling of `Style/NumericLiterals`.
#{file}:1:26: C: Department name is missing.
#{file}:1:41: C: Trailing whitespace detected.
RESULT
end
end
end
end
describe '-E/--extra-details' do
it 'shows extra details' do
create_file('example1.rb',
'puts 0 # rubocop:disable Style/NumericLiterals ')
create_file('.rubocop.yml', <<~YAML)
Layout/TrailingWhitespace:
Details: Trailing space is just sloppy.
YAML
file = abs('example1.rb')
expect(cli.run(['--format', 'emacs', '--extra-details',
'example1.rb'])).to eq(1)
expect($stdout.string).to eq(<<~RESULT)
#{file}:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
#{file}:1:8: W: Lint/RedundantCopDisableDirective: Unnecessary disabling of `Style/NumericLiterals`.
#{file}:1:47: C: Layout/TrailingWhitespace: Trailing whitespace detected. Trailing space is just sloppy.
RESULT
expect($stderr.string).to eq('')
end
end
describe '-S/--display-style-guide' do
it 'shows style guide entry' do
create_file('example1.rb', 'puts 0 ')
file = abs('example1.rb')
url =
'https://rubystyle.guide#no-trailing-whitespace'
expect(cli.run(['--format',
'emacs',
'--display-style-guide',
'example1.rb'])).to eq(1)
expect($stdout.string.lines.to_a[-1])
.to eq("#{file}:1:7: C: Layout/TrailingWhitespace: " \
"Trailing whitespace detected. (#{url})\n")
end
it 'shows reference entry' do
create_file('example1.rb', "JSON.load('{}')")
file = abs('example1.rb')
url = 'https://ruby-doc.org/stdlib-2.3.0/libdoc/json/rdoc/JSON.html' \
'#method-i-load'
expect(cli.run(['--format',
'emacs',
'--display-style-guide',
'example1.rb'])).to eq(1)
output = "#{file}:1:6: C: Security/JSONLoad: " \
"Prefer `JSON.parse` over `JSON.load`. (#{url})"
expect($stdout.string.lines.to_a[-1])
.to eq([output, ''].join("\n"))
end
it 'shows style guide and reference entries' do
create_file('example1.rb', '$foo = 1')
file = abs('example1.rb')
style_guide_link = 'https://rubystyle.guide' \
'#instance-vars'
reference_link = 'https://www.zenspider.com/ruby/quickref.html'
expect(cli.run(['--format',
'emacs',
'--display-style-guide',
'example1.rb'])).to eq(1)
output = "#{file}:1:1: C: Style/GlobalVars: " \
'Do not introduce global variables. ' \
"(#{style_guide_link}, #{reference_link})"
expect($stdout.string.lines.to_a[-1])
.to eq([output, ''].join("\n"))
end
end
describe '--show-cops' do
shared_examples('prints config') do
it 'prints the current configuration' do
out = stdout.lines.to_a
printed_config = YAML.load(out.join) # rubocop:disable Security/YAMLLoad
cop_names = (arguments[0] || '').split(',')
cop_names.each do |cop_name|
global_conf[cop_name].each do |key, value|
printed_value = printed_config[cop_name][key]
expect(printed_value).to eq(value)
end
end
end
end
let(:cops) { RuboCop::Cop::Cop.all }
let(:registry) { RuboCop::Cop::Cop.registry }
let(:global_conf) do
config_path =
RuboCop::ConfigLoader.configuration_file_for(Dir.pwd.to_s)
RuboCop::ConfigLoader.configuration_from_file(config_path)
end
let(:stdout) { $stdout.string }
before do
create_file('.rubocop.yml', <<~YAML)
Layout/LineLength:
Max: 110
YAML
# expect(cli.run(['--show-cops'] + arguments)).to eq(0)
cli.run(['--show-cops'] + arguments)
end
context 'with no args' do
let(:arguments) { [] }
# Extracts the first line out of the description
def short_description_of_cop(cop)
desc = full_description_of_cop(cop)
desc ? desc.lines.first.strip : ''
end
# Gets the full description of the cop or nil if no description is set.
def full_description_of_cop(cop)
cop_config = global_conf.for_cop(cop)
cop_config['Description']
end
it 'prints all available cops and their description' do
cops.each do |cop|
expect(stdout).to include cop.cop_name
# Because of line breaks, we will only find the beginning.
expect(stdout).to include short_description_of_cop(cop)[0..60]
end
end
it 'prints all departments' do
registry.departments.each do |department|
expect(stdout).to include(department.to_s)
end
end
it 'prints all cops in their right department listing' do
lines = stdout.lines
lines.slice_before(/Department /).each do |slice|
departments = registry.departments.map(&:to_s)
current =
departments.delete(slice.shift[/Department '(?<c>[^']+)'/, 'c'])
# all cops in their department listing
registry.with_department(current).each do |cop|
expect(slice.any? { |l| l.include? cop.cop_name }).to be_truthy
end
# no cop in wrong department listing
departments.each do |department|
registry.with_department(department).each do |cop|
expect(slice.any? { |l| l.include? cop.cop_name }).to be_falsey
end
end
end
end
include_examples 'prints config'
end
context 'with one cop given' do
let(:arguments) { ['Layout/Tab'] }
it 'prints that cop and nothing else' do
expect(stdout).to match(
['# Supports --auto-correct',
'Layout/Tab:',
' Description: No hard tabs.',
/^ StyleGuide: ('|")#spaces-indentation('|")$/,
' Enabled: true',
/^ VersionAdded: '[0-9\.]+'$/,
/^ VersionChanged: '[0-9\.]+'$/,
' IndentationWidth:'].join("\n")
)
end
include_examples 'prints config'
end
context 'with two cops given' do
let(:arguments) { ['Layout/Tab,Layout/LineLength'] }
include_examples 'prints config'
end
context 'with one of the cops misspelled' do
let(:arguments) { ['Layout/Tab,Lint/X123'] }
it 'skips the unknown cop' do
expect(stdout).to match(
['# Supports --auto-correct',
'Layout/Tab:',
' Description: No hard tabs.',
/^ StyleGuide: ('|")#spaces-indentation('|")$/,
' Enabled: true'].join("\n")
)
end
end
context 'with --force-default-config' do
let(:arguments) { ['Layout/LineLength', '--force-default-config'] }
it 'prioritizes default config' do
expect(YAML.safe_load(stdout)['Layout/LineLength']['Max']).to eq(80)
end
end
end
describe '-f/--format' do
let(:target_file) { 'example.rb' }
before do
create_file(target_file, '#' * 90)
end
describe 'builtin formatters' do
context 'when simple format is specified' do
it 'outputs with simple format' do
cli.run(['--format', 'simple', 'example.rb'])
expect($stdout.string)
.to include(<<~RESULT)
== #{target_file} ==
C: 1: 1: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
C: 1: 81: Layout/LineLength: Line is too long. [90/80]
1 file inspected, 2 offenses detected
RESULT
end
end
%w[html json].each do |format|
context "when #{format} format is specified" do
context 'and offenses come from the cache' do
context 'and a message has binary encoding' do
let(:message_from_cache) do
(+'Cyclomatic complexity for 文 is too high. [8/6]')
.force_encoding('ASCII-8BIT')
end
let(:data_from_cache) do
[
{
'severity' => 'convention',
'location' => { 'begin_pos' => 18, 'end_pos' => 21 },
'message' => message_from_cache,
'cop_name' => 'Metrics/CyclomaticComplexity',
'status' => 'unsupported'
}
]
end
it "outputs #{format.upcase} code without crashing" do
create_file('example.rb', <<~RUBY)
def 文
b if a
b if a
b if a
b if a
b if a
b if a
b if a
end
RUBY
# Stub out the JSON.load call used by the cache mechanism, so
# we can test what happens when an offense message has
# ASCII-8BIT encoding and contains a non-7bit-ascii character.
allow(JSON).to receive(:load).and_return(data_from_cache)
2.times do
# The second run (and possibly the first) should hit the
# cache.
expect(cli.run(['--format', format,
'--only', 'Metrics/CyclomaticComplexity']))
.to eq(1)
end
expect($stderr.string).to eq('')
end
end
end
end
end
context 'when clang format is specified' do
it 'outputs with clang format' do
create_file('example1.rb', ['x= 0 ',
'#' * 85,
'y ',
'puts x'])
create_file('example2.rb', <<~RUBY)
# frozen_string_literal: true
\tx
def a
puts
end
RUBY
create_file('example3.rb', <<~RUBY)
def badName
if something
test
end
end
RUBY
expect(cli.run(['--format', 'clang', 'example1.rb',
'example2.rb', 'example3.rb']))
.to eq(1)
expect($stdout.string).to eq([
'example1.rb:1:1: C: Style/FrozenStringLiteralComment: ' \
'Missing frozen string literal comment.',
'x= 0 ',
'^',
'example1.rb:1:2: C: Layout/SpaceAroundOperators: ' \
'Surrounding space missing for operator =.',
'x= 0 ',
' ^',
'example1.rb:1:5: C: Layout/TrailingWhitespace: ' \
'Trailing whitespace detected.',
'x= 0 ',
' ^',
'example1.rb:2:81: C: Layout/LineLength: ' \
'Line is too long. [85/80]',
'###################################################' \
'##################################',
' ' \
' ^^^^^',
'example1.rb:3:2: C: Layout/TrailingWhitespace: ' \
'Trailing whitespace detected.',
'y ',
' ^',
'example2.rb:1:1: C: Layout/CommentIndentation: ' \
'Incorrect indentation detected (column 0 instead of 1).',
'# frozen_string_literal: true',
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^',
'example2.rb:3:1: C: Layout/Tab: Tab detected.',
"\tx",
'^',
'example2.rb:3:2: C: Layout/InitialIndentation: ' \
'Indentation of first line in file detected.',
"\tx",
' ^',
'example2.rb:4:1: C: Layout/IndentationConsistency: ' \
'Inconsistent indentation detected.',
'def a ...',
'^^^^^',
'example2.rb:5:1: C: Layout/IndentationWidth: ' \
'Use 2 (not 3) spaces for indentation.',
' puts',
'^^^',
'example3.rb:1:1: C: Style/FrozenStringLiteralComment: ' \
'Missing frozen string literal comment.',
'def badName',
'^',
'example3.rb:1:5: C: Naming/MethodName: ' \
'Use snake_case for method names.',
'def badName',
' ^^^^^^^',
'example3.rb:2:3: C: Style/GuardClause: ' \
'Use a guard clause (return unless something) instead of ' \
'wrapping the code inside a conditional expression.',
' if something',