summaryrefslogtreecommitdiff
path: root/rubocop/cop/rspec/env_assignment.rb
blob: 257454af0e1112d8a61c14e4ac1c29dccf44d288 (plain)
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
require 'rubocop-rspec'
require_relative '../../spec_helpers'

module RuboCop
  module Cop
    module RSpec
      # This cop checks for ENV assignment in specs
      #
      # @example
      #
      #   # bad
      #   before do
      #     ENV['FOO'] = 'bar'
      #   end
      #
      #   # good
      #   before do
      #     stub_env('FOO', 'bar')
      #   end
      class EnvAssignment < Cop
        include SpecHelpers

        MESSAGE = "Don't assign to ENV, use `stub_env` instead.".freeze

        def_node_search :env_assignment?, <<~PATTERN
          (send (const nil? :ENV) :[]= ...)
        PATTERN

        # Following is what node.children looks like on a match
        # [s(:const, nil, :ENV), :[]=, s(:str, "key"), s(:str, "value")]
        def on_send(node)
          return unless in_spec?(node)
          return unless env_assignment?(node)

          add_offense(node, :expression, MESSAGE)
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node.loc.expression, stub_env(env_key(node), env_value(node)))
          end
        end

        def env_key(node)
          node.children[2].source
        end

        def env_value(node)
          node.children[3].source
        end

        def stub_env(key, value)
          "stub_env(#{key}, #{value})"
        end
      end
    end
  end
end