Sha256: ebf7136d9cec14be0a1d979a4ba9b516458902f11886f25abec615475ab30e4c

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module RSpec
      # Checks for `subject` definitions that come after `let` definitions.
      #
      # @example
      #   # bad
      #   RSpec.describe User do
      #     let(:params) { blah }
      #     subject { described_class.new(params) }
      #
      #     it 'is valid' do
      #       expect(subject.valid?).to be(true)
      #     end
      #   end
      #
      #   # good
      #   RSpec.describe User do
      #     subject { described_class.new(params) }
      #
      #     let(:params) { blah }
      #
      #     it 'is valid' do
      #       expect(subject.valid?).to be(true)
      #     end
      #   end
      class LeadingSubject < Cop
        MSG = 'Declare `subject` above any other `let` declarations.'.freeze

        def_node_matcher :subject?, '(block $(send nil :subject ...) args ...)'

        def on_block(node)
          return unless subject?(node) && !in_spec_block?(node)

          node.parent.each_child_node do |sibling|
            break if sibling.equal?(node)

            if sibling.method_name.equal?(:let)
              break add_offense(node, :expression)
            end
          end
        end

        private

        def in_spec_block?(node)
          node.each_ancestor(:block).any? do |ancestor|
            Examples::ALL.include?(ancestor.method_name)
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubocop-rspec-1.13.0 lib/rubocop/cop/rspec/leading_subject.rb