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.'

Constants inherited from Cop

Cop::DEFAULT_CONFIGURATION, Cop::DEFAULT_PATTERN_RE

Constants included from RSpec::Language

RSpec::Language::ALL, RSpec::Language::RSPEC

Instance Method Summary collapse

Methods included from RSpec::TopLevelDescribe

#on_send

Methods inherited from Cop

inherited, #relevant_file?

Instance Method Details

#expectation?(node) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
77
# File 'lib/rubocop/cop/rspec/subject_stub.rb', line 73

def expectation?(node)
  return if all_matcher?(node)

  receive_message?(node)
end

#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)

source that not matches

expect(foo).to all(receive(:bar))


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

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

#on_block(node) ⇒ Object



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

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

  find_subject_stub(node) do |stub|
    add_offense(stub, location: :expression)
  end
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