Skip to content

Commit

Permalink
Improve readability of #check_previous_nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
bquorning committed Jul 14, 2020
1 parent 887a06d commit fb10f1e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
20 changes: 12 additions & 8 deletions lib/rubocop/cop/rspec/leading_subject.rb
Expand Up @@ -43,20 +43,24 @@ def on_block(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, sibling)
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 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
Expand Down
25 changes: 25 additions & 0 deletions spec/rubocop/cop/rspec/leading_subject_spec.rb
Expand Up @@ -135,4 +135,29 @@
end
RUBY
end

it 'checks also when subject is below a non-offending node' do
expect_offense(<<~RUBY)
RSpec.describe do
def helper_method
end
it { is_expected.to be_present }
subject { described_class.new }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Declare `subject` above any other `it` declarations.
end
RUBY

expect_correction(<<~RUBY)
RSpec.describe do
def helper_method
end
subject { described_class.new }
it { is_expected.to be_present }
end
RUBY
end
end

0 comments on commit fb10f1e

Please sign in to comment.