Class: RuboCop::Cop::RSpec::DescribedClass

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/rspec/described_class.rb

Overview

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.

There's a known caveat with rspec-rails's `controller` helper that runs its block in a different context, and `described_class` is not available to it. `SkipBlocks` option excludes detection in all non-RSpec related blocks.

To narrow down this setting to only a specific directory, it is possible to use an overriding configuration file local to that directory.

Examples:

`EnforcedStyle: described_class`

# bad
describe MyClass do
  subject { MyClass.do_something }
end

# good
describe MyClass do
  subject { described_class.do_something }
end

`EnforcedStyle: explicit`

# bad
describe MyClass do
  subject { described_class.do_something }
end

# good
describe MyClass do
  subject { MyClass.do_something }
end

`SkipBlocks: true`

# spec/controllers/.rubocop.yml
# RSpec/DescribedClass:
#   SkipBlocks: true

# acceptable
describe MyConcern do
  controller(ApplicationController) do
    include MyConcern
  end
end

Constant Summary collapse

DESCRIBED_CLASS =
'described_class'
MSG =
'Use `%<replacement>s` instead of `%<src>s`.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Instance Method Details

#on_block(node) ⇒ Object


80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/rubocop/cop/rspec/described_class.rb', line 80

def on_block(node)
  # In case the explicit style is used, we need to remember what's
  # being described.
  @described_class, body = described_constant(node)

  return unless body

  find_usage(body) do |match|
    msg = message(match.const_name)
    add_offense(match, message: msg) do |corrector|
      autocorrect(corrector, match)
    end
  end
end