Class: RuboCop::Cop::RSpec::LetSetup

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rspec/let_setup.rb

Overview

Checks unreferenced ‘let!` calls being used for test setup.

Examples:

# bad
let!(:my_widget) { create(:widget) }

it 'counts widgets' do
  expect(Widget.count).to eq(1)
end

# good
it 'counts widgets' do
  create(:widget)
  expect(Widget.count).to eq(1)
end

# good
before { create(:widget) }

it 'counts widgets' do
  expect(Widget.count).to eq(1)
end

Constant Summary collapse

MSG =
'Do not use `let!` to setup objects not referenced in tests.'

Instance Method Summary collapse

Methods inherited from Base

inherited, #on_new_investigation

Methods included from RSpec::Language::NodePattern

#block_or_numblock_pattern, #block_pattern, #numblock_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #explicit_rspec?, #hook?, #include?, #let?, #rspec?, #shared_group?, #spec_group?, #subject?

Instance Method Details

#example_or_shared_group_or_including?(node) ⇒ Object



32
33
34
35
36
37
# File 'lib/rubocop/cop/rspec/let_setup.rb', line 32

def_node_matcher :example_or_shared_group_or_including?, <<~PATTERN
  (block {
    (send #rspec? {#SharedGroups.all #ExampleGroups.all} ...)
    (send nil? #Includes.all ...)
  } ...)
PATTERN

#let_bang(node) ⇒ Object



40
41
42
43
44
45
# File 'lib/rubocop/cop/rspec/let_setup.rb', line 40

def_node_matcher :let_bang, <<~PATTERN
  {
    (block $(send nil? :let! {(sym $_) (str $_)}) ...)
    $(send nil? :let! {(sym $_) (str $_)} block_pass)
  }
PATTERN

#method_called?(node) ⇒ Object



48
# File 'lib/rubocop/cop/rspec/let_setup.rb', line 48

def_node_search :method_called?, '(send nil? %)'

#on_block(node) ⇒ Object

rubocop:disable InternalAffairs/NumblockHandler



50
51
52
53
54
55
56
# File 'lib/rubocop/cop/rspec/let_setup.rb', line 50

def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
  return unless example_or_shared_group_or_including?(node)

  unused_let_bang(node) do |let|
    add_offense(let)
  end
end