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

Inherits:
RuboCop::Cop show all
Includes:
RSpec::TopLevelDescribe
Defined in:
lib/rubocop/cop/rspec/described_class.rb

Overview

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 =
'
  :after
  :around
  :before
  :context
  :describe
  :example
  :example_group
  :fcontext
  :fdescribe
  :feature
  :fexample
  :ffeature
  :fit
  :focus
  :fscenario
  :fspecify
  :it
  :let
  :let!
  :scenario
  :specify
  :xcontext
  :xdescribe
  :xexample
  :xfeature
  :xit
  :xscenario
  :xspecify
'.freeze

Instance Method Summary collapse

Methods included from RSpec::TopLevelDescribe

#on_send

Instance Method Details

#autocorrect(node) ⇒ Object



80
81
82
83
84
# File 'lib/rubocop/cop/rspec/described_class.rb', line 80

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

#on_block(node) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/rubocop/cop/rspec/described_class.rb', line 71

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