Class: RuboCop::Cop::RSpec::SubjectStub

Inherits:
RuboCop::Cop show all
Includes:
RSpec::Language, RSpec::Language::NodePattern, RSpec::SpecOnly, RSpec::TopLevelDescribe
Defined in:
lib/rubocop/cop/rspec/subject_stub.rb

Overview

Checks for stubbed test subjects.

Examples:

# bad
describe Foo do
  subject(:bar) { baz }

  before do
    allow(bar).to receive(:qux?).and_return(true)
  end
end

See Also:

Constant Summary collapse

MSG =
'Do not stub your test subject.'.freeze

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Methods included from RSpec::TopLevelDescribe

#on_send

Instance Method Details

#message_expectation?(node, method_name) ⇒ Object

Match ‘allow` and `expect(…).to receive`

Examples:

source that matches

allow(foo).to  receive(:bar)
allow(foo).to  receive(:bar).with(1)
allow(foo).to  receive(:bar).with(1).and_return(2)
expect(foo).to receive(:bar)
expect(foo).to receive(:bar).with(1)
expect(foo).to receive(:bar).with(1).and_return(2)


61
62
63
64
65
66
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 61

def_node_matcher :message_expectation?, <<-PATTERN
  {
    (send nil :allow (send nil %))
    (send (send nil :expect (send nil %)) :to #receive_message?)
  }
PATTERN

#on_block(node) ⇒ Object



70
71
72
73
74
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 70

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

  find_subject_stub(node) { |stub| add_offense(stub, :expression) }
end

#subject(node) {|Symbol| ... } ⇒ Object

Find a named or unnamed subject definition

Examples:

anonymous subject

subject(parse('subject { foo }').ast) do |name|
  name # => :subject
end

named subject

subject(parse('subject(:thing) { foo }').ast) do |name|
  name # => :thing
end

Parameters:

  • node (RuboCop::Node)

Yields:

  • (Symbol)

    subject name



44
45
46
47
48
49
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 44

def_node_matcher :subject, <<-PATTERN
{
  (block (send nil :subject (sym $_)) args ...)
  (block (send nil $:subject) args ...)
}
PATTERN