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

Inherits:
RuboCop::Cop show all
Includes:
RSpec::SpecOnly, RSpec::TopLevelDescribe
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 should be used instead of repeating the class.

Examples:

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

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

Constant Summary collapse

DESCRIBED_CLASS =
'described_class'.freeze
MSG =
"Use `#{DESCRIBED_CLASS}` instead of `%s`".freeze
RSPEC_BLOCK_METHODS =
RuboCop::RSpec::Language::ALL.to_node_pattern

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Methods included from RSpec::TopLevelDescribe

#on_send

Instance Method Details

#autocorrect(node) ⇒ Object



49
50
51
52
53
# File 'lib/rubocop/cop/rspec/described_class.rb', line 49

def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.loc.expression, DESCRIBED_CLASS)
  end
end

#on_block(node) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/rspec/described_class.rb', line 40

def on_block(node)
  describe, described_class, body = described_constant(node)
  return unless top_level_describe?(describe)

  find_constant_usage(body, described_class) do |match|
    add_offense(match, :expression, format(MSG, match.const_name))
  end
end