debian-mirror-gitlab/rubocop/cop/rspec/env_assignment.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

55 lines
1.3 KiB
Ruby
Raw Normal View History

2019-12-04 20:38:33 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
2022-11-25 23:54:43 +05:30
require 'rubocop-rspec'
2018-03-17 18:26:18 +05:30
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
2022-10-11 01:57:18 +05:30
class EnvAssignment < RuboCop::Cop::Base
extend RuboCop::Cop::AutoCorrector
2021-04-29 21:17:54 +05:30
MESSAGE = "Don't assign to ENV, use `stub_env` instead."
2018-03-17 18:26:18 +05:30
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 env_assignment?(node)
2022-10-11 01:57:18 +05:30
add_offense(node, message: MESSAGE) do |corrector|
2018-03-17 18:26:18 +05:30
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