Class: RuboCop::Cop::RSpec::NoExpectationExample

Inherits:
Base
  • Object
show all
Includes:
AllowedPattern, SkipOrPending
Defined in:
lib/rubocop/cop/rspec/no_expectation_example.rb

Overview

Checks if an example contains any expectation.

All RSpec’s example and expectation methods are covered by default. If you are using your own custom methods, add the following configuration:

RSpec:
  Language:
    Examples:
      Regular:
        - custom_it
    Expectations:
      - custom_expect

This cop can be customized with an allowed expectation methods pattern with an ‘AllowedPatterns` option. ^expect_ and ^assert_ are allowed by default.

Examples:

# bad
it do
  a?
end

# good
it do
  expect(a?).to be(true)
end

‘AllowedPatterns` configuration


# .rubocop.yml
# RSpec/NoExpectationExample:
#   AllowedPatterns:
#     - ^expect_
#     - ^assert_
# bad
it do
  not_expect_something
end

# good
it do
  expect_something
end

it do
  assert_something
end

Constant Summary collapse

MSG =
'No expectation found in this example.'

Instance Method Summary collapse

Methods included from SkipOrPending

#skip_or_pending_inside_block?, #skipped_in_metadata?

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

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

#includes_expectation?(node) ⇒ Boolean

Parameters:

  • node (RuboCop::AST::Node)

Returns:

  • (Boolean)


74
75
76
77
78
79
# File 'lib/rubocop/cop/rspec/no_expectation_example.rb', line 74

def_node_search :includes_expectation?, <<~PATTERN
  {
    (send nil? #Expectations.all ...)
    (send nil? `#matches_allowed_pattern? ...)
  }
PATTERN

#includes_skip_example?(node) ⇒ Boolean

Parameters:

  • node (RuboCop::AST::Node)

Returns:

  • (Boolean)


84
85
86
# File 'lib/rubocop/cop/rspec/no_expectation_example.rb', line 84

def_node_search :includes_skip_example?, <<~PATTERN
  (send nil? {:pending :skip} ...)
PATTERN

#on_block(node) ⇒ Object Also known as: on_numblock

Parameters:

  • node (RuboCop::AST::BlockNode)


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

def on_block(node)
  return unless regular_or_focused_example?(node)
  return if includes_expectation?(node)
  return if includes_skip_example?(node)
  return if skipped_in_metadata?(node.send_node)

  add_offense(node)
end

#regular_or_focused_example?(node) ⇒ Boolean

Parameters:

  • node (RuboCop::AST::Node)

Returns:

  • (Boolean)


67
68
69
# File 'lib/rubocop/cop/rspec/no_expectation_example.rb', line 67

def_node_matcher :regular_or_focused_example?, <<~PATTERN
  ({block numblock} (send nil? {#Examples.regular #Examples.focused} ...) ...)
PATTERN