-
Notifications
You must be signed in to change notification settings - Fork 10
/
bundler_setup_in_tests.rb
65 lines (56 loc) · 2.19 KB
/
bundler_setup_in_tests.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
# frozen_string_literal: true
require "rubocop/packaging/lib_helper_module"
module RuboCop # :nodoc:
module Cop # :nodoc:
module Packaging # :nodoc:
# This cop flags the `require "bundler/setup"` calls if they're
# made from inside the tests directory.
#
# @example
#
# # bad
# require "foo"
# require "bundler/setup"
#
# # good
# require "foo"
#
class BundlerSetupInTests < Base
include RuboCop::Packaging::LibHelperModule
# This is the message that will be displayed when RuboCop::Packaging finds
# an offense of using `require "bundler/setup"` in the tests directory.
MSG = "Avoid using `bundler/setup` in your tests."
def_node_matcher :bundler_setup?, <<~PATTERN
(send nil? :require
(str #bundler_setup_in_test_dir?))
PATTERN
# Extended from the Base class.
# More about the `#on_new_investigation` method can be found here:
# https://github.com/rubocop-hq/rubocop/blob/343f62e4555be0470326f47af219689e21c61a37/lib/rubocop/cop/base.rb
#
# Processing of the AST happens here.
def on_new_investigation
@file_path = processed_source.file_path
@file_directory = File.dirname(@file_path)
end
# Extended from AST::Traversal.
# More about the `#on_send` method can be found here:
# https://github.com/rubocop-hq/rubocop-ast/blob/08d0f49a47af1e9a30a6d8f67533ba793c843d67/lib/rubocop/ast/traversal.rb#L112
def on_send(node)
return unless bundler_setup?(node)
add_offense(node)
end
# This method is called from inside `#def_node_matcher`.
# It flags an offense if the `require "bundler/setup"`
# call is made from the tests directory.
def bundler_setup_in_test_dir?(str)
str.eql?("bundler/setup") && falls_in_test_dir?
end
# This method determines if the call is made *from* the tests directory.
def falls_in_test_dir?
%w[spec specs test tests].any? { |dir| File.expand_path(@file_directory).start_with?("#{root_dir}/#{dir}") }
end
end
end
end
end