lib/rubocop/cop/rspec/leading_subject.rb in rubocop-rspec-1.42.0 vs lib/rubocop/cop/rspec/leading_subject.rb in rubocop-rspec-1.43.0

- old
+ new

@@ -29,11 +29,11 @@ # # good # subject { described_class.new(params) } # it { expect_something } # it { expect_something_else } # - class LeadingSubject < Cop + class LeadingSubject < Base extend AutoCorrector MSG = 'Declare `subject` above any other `%<offending>s` declarations.' def on_block(node) @@ -41,36 +41,39 @@ check_previous_nodes(node) end def check_previous_nodes(node) - node.parent.each_child_node do |sibling| - if offending?(sibling) - msg = format(MSG, offending: sibling.method_name) - add_offense(node, message: msg) do |corrector| - autocorrect(corrector, node) - end + offending_node(node) do |offender| + msg = format(MSG, offending: offender.method_name) + add_offense(node, message: msg) do |corrector| + autocorrect(corrector, node, offender) end - - break if offending?(sibling) || sibling.equal?(node) end end private - def autocorrect(corrector, node) - first_node = find_first_offending_node(node) + def offending_node(node) + node.parent.each_child_node.find do |sibling| + break if sibling.equal?(node) + + yield sibling if offending?(sibling) + end + end + + def autocorrect(corrector, node, sibling) RuboCop::RSpec::Corrector::MoveNode.new( node, corrector, processed_source - ).move_before(first_node) + ).move_before(sibling) end def offending?(node) - let?(node) || hook?(node) || example?(node) - end - - def find_first_offending_node(node) - node.parent.children.find { |sibling| offending?(sibling) } + let?(node) || + hook?(node) || + example?(node) || + spec_group?(node) || + include?(node) end def in_spec_block?(node) node.each_ancestor(:block).any? do |ancestor| example?(ancestor)