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

Inherits:
Cop
  • Object
show all
Includes:
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 inherited from Cop

Cop::DEFAULT_CONFIGURATION

Constants included from RSpec::Language

RSpec::Language::ALL

Instance Method Summary collapse

Methods included from RSpec::TopLevelDescribe

#on_send

Methods inherited from Cop

inherited, #relevant_file?

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)


58
59
60
61
62
63
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 58

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



67
68
69
70
71
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 67

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



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

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