lib/rubocop/cop/rspec/described_class.rb in rubocop-rspec-2.27.0 vs lib/rubocop/cop/rspec/described_class.rb in rubocop-rspec-2.27.1
- old
+ new
@@ -6,12 +6,14 @@
# Checks that tests use `described_class`.
#
# If the first argument of describe is a class, the class is exposed to
# each example via described_class.
#
- # This cop can be configured using the `EnforcedStyle` and `SkipBlocks`
- # options.
+ # This cop can be configured using the `EnforcedStyle`, `SkipBlocks`
+ # and `OnlyStaticConstants` options.
+ # `OnlyStaticConstants` is only relevant when `EnforcedStyle` is
+ # `described_class`.
#
# @example `EnforcedStyle: described_class` (default)
# # bad
# describe MyClass do
# subject { MyClass.do_something }
@@ -20,10 +22,22 @@
# # good
# describe MyClass do
# subject { described_class.do_something }
# end
#
+ # @example `OnlyStaticConstants: true` (default)
+ # # good
+ # describe MyClass do
+ # subject { MyClass::CONSTANT }
+ # end
+ #
+ # @example `OnlyStaticConstants: false`
+ # # bad
+ # describe MyClass do
+ # subject { MyClass::CONSTANT }
+ # end
+ #
# @example `EnforcedStyle: explicit`
# # bad
# describe MyClass do
# subject { described_class.do_something }
# end
@@ -52,11 +66,11 @@
# controller(ApplicationController) do
# include MyConcern
# end
# end
#
- class DescribedClass < Base
+ class DescribedClass < Base # rubocop:disable Metrics/ClassLength
extend AutoCorrector
include ConfigurableEnforcedStyle
include Namespace
DESCRIBED_CLASS = 'described_class'
@@ -110,18 +124,21 @@
corrector.replace(match, replacement)
end
def find_usage(node, &block)
yield(node) if offensive?(node)
+ return if scope_change?(node) || allowed?(node)
- return if scope_change?(node)
-
node.each_child_node do |child|
find_usage(child, &block)
end
end
+ def allowed?(node)
+ node.const_type? && only_static_constants?
+ end
+
def message(offense)
if style == :described_class
format(MSG, replacement: DESCRIBED_CLASS, src: offense)
else
format(MSG, replacement: @described_class.const_name,
@@ -135,9 +152,13 @@
skippable_block?(node)
end
def skippable_block?(node)
node.block_type? && !rspec_block?(node) && cop_config['SkipBlocks']
+ end
+
+ def only_static_constants?
+ cop_config.fetch('OnlyStaticConstants', true)
end
def offensive?(node)
if style == :described_class
offensive_described_class?(node)