rubocop-rspec: Bug: false positive of RSpec/LetSetup with context and outer shared_examples

This issue produces false positives of Rspec/LetSetup with the latest rubocop-rspec (1.36.0) when we put let! inside some context and we also have shared_examples referencing that let! outside the context.

Something like this:

shared_examples 'some shared example' do
  it 'checks something' do
    is_expected.to eq user
  end
end

context 'when inside some context' do
  let!(:user) { create :user }

  include_examples 'some shared example'
end

If we are to run rubocop-rspec on the code above it would produce the following:

spec/test_spec.rb:8:3: C: RSpec/LetSetup: Do not use let! to setup objects not referenced in tests.
  let!(:user) { create :user }
  ^^^^^^^^^^^

1 file inspected, 1 offense detected

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 15
  • Comments: 32 (16 by maintainers)

Commits related to this issue

Most upvoted comments

I’m fairly certain this isn’t limited to shared examples.

If you have a top-level subject and create an object inside a context with a let!, you will get the same false positive.

I.e.

subject(:foo) do
  post "url",
    params: {
      id: my_object.id
    }
end

context "when calling the method" do
  let!(:my_object) { FactoryBot.create(object) } # you will get a false positive here
  
  it { .. }
end

I’m using 1.42.0 and it’s giving me it for that example (when I remove the rubocop:disable marker):

Inspecting 1 file
C

Offenses:

spec/test.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
describe 'foo' do
^
spec/test.rb:3:5: C: RSpec/LetSetup: Do not use let! to setup objects not referenced in tests. (https://www.rubydoc.info/gems/rubocop-rspec/RuboCop/Cop/RSpec/LetSetup)
    let!(:record) do
    ^^^^^^^^^^^^^

1 file inspected, 2 offenses detected
subject(:update_user) { user.update(name:) }

expect { update_user }.to ...

This is prone to incidental state. subject/let memoize their result, and won’t run twice, which immediately makes them a bad fit for some cases, e.g.

subject(:remove_top_card) { cards.pop }
it "removes two cards" do
  expect { remove_top_card }.to change { cards.count }.to(1)
  expect { remove_top_card }.to change { cards.count }.to(0) # 💥 
end

There’s no point in abusing this mechanism, define a helper method:

def remove_top_card = cards.pop

def update_user = user.update(name:)

Also mind implicit block expectations.

I’ve hit this when using let! in shared_context, which is the reverse situation.