Class: RuboCop::Cop::RSpec::UnspecifiedException

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/unspecified_exception.rb

Overview

Checks for a specified error in checking raised errors.

Enforces one of an Exception type, a string, or a regular expression to match against the exception message as a parameter to `raise_error`

Examples:


# bad
expect {
  raise StandardError.new('error')
}.to raise_error

# good
expect {
  raise StandardError.new('error')
}.to raise_error(StandardError)

expect {
  raise StandardError.new('error')
}.to raise_error('error')

expect {
  raise StandardError.new('error')
}.to raise_error(/err/)

expect { do_something }.not_to raise_error

Constant Summary collapse

MSG =
'Specify the exception being captured'
RESTRICT_ON_SEND =
%i[to].freeze

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#block_with_args?(node) ⇒ Boolean

Returns:

  • (Boolean)

57
58
59
60
61
# File 'lib/rubocop/cop/rspec/unspecified_exception.rb', line 57

def block_with_args?(node)
  return unless node&.block_type?

  node.arguments?
end

#empty_exception_matcher?(node) ⇒ Boolean

Returns:

  • (Boolean)

53
54
55
# File 'lib/rubocop/cop/rspec/unspecified_exception.rb', line 53

def empty_exception_matcher?(node)
  empty_raise_error_or_exception(node) && !block_with_args?(node.parent)
end

#empty_raise_error_or_exception(node) ⇒ Object


38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rspec/unspecified_exception.rb', line 38

def_node_matcher :empty_raise_error_or_exception, <<-PATTERN
  (send
    (block
        (send nil? :expect) ...)
    :to
    (send nil? {:raise_error :raise_exception})
  )
PATTERN

#on_send(node) ⇒ Object


47
48
49
50
51
# File 'lib/rubocop/cop/rspec/unspecified_exception.rb', line 47

def on_send(node)
  return unless empty_exception_matcher?(node)

  add_offense(node.children.last)
end