Skip to content

RSpec/LetSetup false positive with nested groups #2075

@dgmora

Description

@dgmora

I realize this is similar to #830, but this one here is happening without shared examples:

# frozen_string_literal: true

describe User, type: :model do
  let!(:user) { create(:user) }

  it 'is valid' do
    expect(user).to be_valid
  end

  context 'with no direct usage' do
    let!(:user) { create(:user, :special) } # <-- offense, but shouldn't!

    it 'creates something' do
      expect(SomeModel.count).to eq(2)
    end
  end
end

The second let declaration is constrained by a higher level let!. The let! is part of the setup, so changing the second let to before { ... } may not work, since the user will already be created and you are now creating a second user. You can't also change the first one, because it is used in another test.

I see that this could be refactored to let(:user) plus before. But it still looks like a false positive to me because is not actually possible to change that second let! to a before block. The first usage of let! is legit. I don't think you should refactor the whole test just to comply with RSpec/LetSetup


Expected behavior

If the same let! is declared in a higher level, those on the lower level shouldn't be marked as an offense because it's not possible to determine if you can change it to a before or not.

Actual behavior

The second let reports RSpec/LetSetup

Steps to reproduce the problem

See above

RuboCop RSpec version

$ bundle exec rubocop -V
1.74.0 (using Parser 3.3.7.2, rubocop-ast 1.38.1, analyzing as Ruby 3.3, running on ruby 3.3.6) [arm64-darwin23]
  - rubocop-performance 1.24.0
  - rubocop-factory_bot 2.27.1
  - rubocop-rails 2.30.3
  - rubocop-rspec 3.5.0
  - rubocop-rspec_rails 2.31.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions