File: be_nil.rb

package info (click to toggle)
ruby-rubocop-rspec 2.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,892 kB
  • sloc: ruby: 22,283; makefile: 4
file content (74 lines) | stat: -rw-r--r-- 1,927 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Ensures a consistent style is used when matching `nil`.
      #
      # You can either use the more specific `be_nil` matcher, or the more
      # generic `be` matcher with a `nil` argument.
      #
      # This cop can be configured using the `EnforcedStyle` option
      #
      # @example `EnforcedStyle: be_nil` (default)
      #   # bad
      #   expect(foo).to be(nil)
      #
      #   # good
      #   expect(foo).to be_nil
      #
      # @example `EnforcedStyle: be`
      #   # bad
      #   expect(foo).to be_nil
      #
      #   # good
      #   expect(foo).to be(nil)
      #
      class BeNil < Base
        extend AutoCorrector
        include ConfigurableEnforcedStyle

        BE_MSG = 'Prefer `be(nil)` over `be_nil`.'
        BE_NIL_MSG = 'Prefer `be_nil` over `be(nil)`.'
        RESTRICT_ON_SEND = %i[be be_nil].freeze

        # @!method be_nil_matcher?(node)
        def_node_matcher :be_nil_matcher?, <<-PATTERN
          (send nil? :be_nil)
        PATTERN

        # @!method nil_value_expectation?(node)
        def_node_matcher :nil_value_expectation?, <<-PATTERN
          (send nil? :be nil)
        PATTERN

        def on_send(node)
          case style
          when :be
            check_be_style(node)
          when :be_nil
            check_be_nil_style(node)
          end
        end

        private

        def check_be_style(node)
          return unless be_nil_matcher?(node)

          add_offense(node, message: BE_MSG) do |corrector|
            corrector.replace(node.loc.expression, 'be(nil)')
          end
        end

        def check_be_nil_style(node)
          return unless nil_value_expectation?(node)

          add_offense(node, message: BE_NIL_MSG) do |corrector|
            corrector.replace(node.loc.expression, 'be_nil')
          end
        end
      end
    end
  end
end