Sha256: ff524b5cc1f19b72635e0df931ef887fdbfbd1e702dacfc39c1d7257e109bfd6

Contents?: true

Size: 1.45 KB

Versions: 13

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Do not use `expect` in hooks such as `before`.
      #
      # @example
      #   # bad
      #   before do
      #     expect(something).to eq 'foo'
      #   end
      #
      #   # bad
      #   after do
      #     expect_any_instance_of(Something).to receive(:foo)
      #   end
      #
      #   # good
      #   it do
      #     expect(something).to eq 'foo'
      #   end
      class ExpectInHook < Cop
        MSG = 'Do not use `%<expect>s` in `%<hook>s` hook'.freeze
        HOOKS = Hooks::ALL.node_pattern_union.freeze

        def_node_matcher :hook, <<-PATTERN
          (block (send _ $#{HOOKS} ...) _ $!nil?)
        PATTERN

        def_node_search :expect, <<-PATTERN
          {
            #{Expectations::ALL.send_pattern}
            #{Expectations::ALL.block_pattern}
          }
        PATTERN

        def on_block(node)
          hook(node) do |hook_name, body|
            expect(body) do |expect|
              method = send_node(expect)
              add_offense(method, location: :selector,
                                  message: message(method, hook_name))
            end
          end
        end

        private

        def message(expect, hook)
          format(MSG, expect: expect.method_name, hook: hook)
        end

        def send_node(node)
          return node if node.send_type?
          node.children.first
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-rspec-1.27.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.26.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.25.1 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.25.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.24.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.23.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.22.2 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.22.1 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.22.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.21.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.20.1 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.20.0 lib/rubocop/cop/rspec/expect_in_hook.rb
rubocop-rspec-1.19.0 lib/rubocop/cop/rspec/expect_in_hook.rb