Class: RuboCop::Cop::RSpec::ImplicitSubject

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

Overview

Checks for usage of implicit subject (‘is_expected` / `should`).

This cop can be configured using the ‘EnforcedStyle` option

Examples:

‘EnforcedStyle: single_line_only` (default)

# bad
it do
  is_expected.to be_truthy
end

# good
it { is_expected.to be_truthy }
it do
  expect(subject).to be_truthy
end

‘EnforcedStyle: single_statement_only`

# bad
it do
  foo = 1
  is_expected.to be_truthy
end

# good
it do
  foo = 1
  expect(subject).to be_truthy
end
it do
  is_expected.to be_truthy
end

‘EnforcedStyle: disallow`

# bad
it { is_expected.to be_truthy }

# good
it { expect(subject).to be_truthy }

‘EnforcedStyle: require_implicit`

# bad
it { expect(subject).to be_truthy }

# good
it { is_expected.to be_truthy }

# bad
it do
  expect(subject).to be_truthy
end

# good
it do
  is_expected.to be_truthy
end

# good
it { expect(named_subject).to be_truthy }

Constant Summary collapse

MSG_REQUIRE_EXPLICIT =
"Don't use implicit subject."
MSG_REQUIRE_IMPLICIT =
"Don't use explicit subject."
RESTRICT_ON_SEND =
%i[
  expect
  is_expected
  should
  should_not
].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#explicit_unnamed_subject?(node) ⇒ Object



81
82
83
# File 'lib/rubocop/cop/rspec/implicit_subject.rb', line 81

def_node_matcher :explicit_unnamed_subject?, <<~PATTERN
  (send nil? :expect (send nil? :subject))
PATTERN

#implicit_subject?(node) ⇒ Object



86
87
88
# File 'lib/rubocop/cop/rspec/implicit_subject.rb', line 86

def_node_matcher :implicit_subject?, <<~PATTERN
  (send nil? {:should :should_not :is_expected} ...)
PATTERN

#on_send(node) ⇒ Object



90
91
92
93
94
95
96
# File 'lib/rubocop/cop/rspec/implicit_subject.rb', line 90

def on_send(node)
  return unless invalid?(node)

  add_offense(node) do |corrector|
    autocorrect(corrector, node)
  end
end