Class: RuboCop::Cop::RSpec::NamedSubject

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/named_subject.rb

Overview

Checks for explicitly referenced test subjects.

RSpec lets you declare an “implicit subject” using ‘subject { … }` which allows for tests like `it { should be_valid }`. If you need to reference your test subject you should explicitly name it using `subject(:your_subject_name) { … }`. Your test subjects should be the most important object in your tests so they deserve a descriptive name.

Examples:

# bad
RSpec.describe User do
  subject { described_class.new }

  it 'is valid' do
    expect(subject.valid?).to be(true)
  end
end

# good
RSpec.describe Foo do
  subject(:user) { described_class.new }

  it 'is valid' do
    expect(user.valid?).to be(true)
  end
end

# also good
RSpec.describe Foo do
  subject(:user) { described_class.new }

  it { should be_valid }
end

Constant Summary collapse

MSG =
'Name your test subject if you need '\
'to reference it explicitly.'.freeze

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#on_block(node) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/rubocop/cop/rspec/named_subject.rb', line 53

def on_block(node)
  return unless rspec_block?(node)

  subject_usage(node) do |subject_node|
    add_offense(subject_node, location: :selector)
  end
end