Sha256: 47fd509128241d5f2df27cb5dacfbf6abeb2a9216fafad924249950441d860e2

Contents?: true

Size: 1.63 KB

Versions: 12

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Checks for consistent message expectation style.
      #
      # This cop can be configured in your configuration using the
      # `EnforcedStyle` option and supports `--auto-gen-config`.
      #
      # @example `EnforcedStyle: allow`
      #
      #   # bad
      #   expect(foo).to receive(:bar)
      #
      #   # good
      #   allow(foo).to receive(:bar)
      #
      # @example `EnforcedStyle: expect`
      #
      #   # bad
      #   allow(foo).to receive(:bar)
      #
      #   # good
      #   expect(foo).to receive(:bar)
      #
      class MessageExpectation < Base
        include ConfigurableEnforcedStyle

        MSG = 'Prefer `%<style>s` for setting message expectations.'

        SUPPORTED_STYLES = %w[allow expect].freeze
        RESTRICT_ON_SEND = %i[to].freeze

        # @!method message_expectation(node)
        def_node_matcher :message_expectation, <<-PATTERN
          (send $(send nil? {:expect :allow} ...) :to #receive_message?)
        PATTERN

        # @!method receive_message?(node)
        def_node_search :receive_message?, '(send nil? :receive ...)'

        def on_send(node)
          message_expectation(node) do |match|
            return correct_style_detected if preferred_style?(match)

            message = format(MSG, style: style)
            add_offense(match.loc.selector, message: message) do
              opposite_style_detected
            end
          end
        end

        private

        def preferred_style?(expectation)
          expectation.method_name.equal?(style)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-rspec-2.9.0/lib/rubocop/cop/rspec/message_expectation.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-rspec-2.9.0/lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.11.1 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.11.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.10.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.9.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.8.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.7.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.6.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.5.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.4.0 lib/rubocop/cop/rspec/message_expectation.rb
rubocop-rspec-2.3.0 lib/rubocop/cop/rspec/message_expectation.rb