Skip to content

RSpec/LetSetup false positive when used only on a block declared on an outer contextΒ #2136

@santiagorodriguez96

Description

@santiagorodriguez96

Similar to #2075, but on this case the false positive is caused when using the variable in a block on an outside context:

# frozen_string_literal: true

describe 'False positive example', type: :system do
  after do
    authenticator.remove!
  end

  context 'that defines an authenticator' do
    let!(:authenticator) { add_virtual_authenticator_with_some_options } # <-- offense, but shouldn't!

    it 'does something without using the authenticator variable' do
      # ...      
    end
  end

  context 'that defines another authenticator' do
    let!(:authenticator) { add_virtual_authenticator_with_other_options } # <-- offense, but shouldn't!

    it 'does something without using the authenticator variable' do
      # ...
    end
  end
end

Note that if the let! is placed at the same level as the block that used the variable, there's no offense:

# frozen_string_literal: true

describe 'False positive example', type: :system do
  let!(:authenticator) { add_virtual_authenticator } # <-- no offense!

  after do
    authenticator.remove!
  end

  context 'that defines an authenticator' do
    it 'does something without using the authenticator variable' do
      # ...      
    end
  end
end

Expected behavior

No offense is emitted as the variables declared in the let!s are being used in the spec – as it happens when the let! is declared at the same level as the block that uses the variable.

Actual behavior

The let!s report an RSpec/LetSetup offense.

RuboCop RSpec version

$ bundle exec rubocop -V
1.81.7 (using Parser 3.3.9.0, rubocop-ast 1.48.0, analyzing as Ruby 2.7, running on ruby 3.4.4) [arm64-darwin24]
  - rubocop-rspec 3.8.0
  - rubocop-rails 2.34.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions