Skip to content

Commit

Permalink
Fix subject nesting detection in RSpec/LeadingSubject
Browse files Browse the repository at this point in the history
For the following code:

    RSpec.describe User do
      let(:foo) { 'bar' }
      it_behaves_like 'a good citizen' do
        subject { described_class.new }
      end
    end

when `on_block` is triggered for `subject`,
`node.parent.each_child_node.to_a` is:

    [
      s(:send, nil, :it_behaves_like, s(:str, "a good citizen")),
      s(:args),
      s(:block, s(:send, nil, :subject), s(:args), s(:send, s(:send, nil, :described_class), :new))
    ]

and autocorrect was putting the subject block above all "offenders"
coming before it, including the `it_behaves_like` send node.
  • Loading branch information
pirj committed Aug 21, 2020
1 parent 054bc95 commit fefb978
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,7 @@

* Add `RSpec/RepeatedIncludeExample` cop. ([@biinari][])
* Fix `RSpec/FilePath` when checking a file with a shared example. ([@pirj][])
* Fix subject nesting detection in `RSpec/LeadingSubject`. ([@pirj][])

## 1.43.1 (2020-08-17)

Expand Down
6 changes: 5 additions & 1 deletion lib/rubocop/cop/rspec/leading_subject.rb
Expand Up @@ -54,13 +54,17 @@ def check_previous_nodes(node)
private

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

yield sibling if offending?(sibling)
end
end

def parent(node)
node.each_ancestor(:block).first.body
end

def autocorrect(corrector, node, sibling)
RuboCop::RSpec::Corrector::MoveNode.new(
node, corrector, processed_source
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/rspec/leading_subject_spec.rb
Expand Up @@ -269,4 +269,16 @@ def helper_method
end
RUBY
end

it 'ignores subject nested inside a block' do
expect_no_offenses(<<-RUBY)
RSpec.describe User do
let(:foo) { 'bar' }
it_behaves_like 'a good citizen' do
subject { described_class.new }
end
end
RUBY
end
end

0 comments on commit fefb978

Please sign in to comment.