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_pattern, #send_pattern

Methods included from RSpec::Language

#example?, #example_group?, #example_group_with_body?, #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
38
39
# File 'lib/rubocop/cop/rspec/let_setup.rb', line 32

def_node_matcher :example_or_shared_group_or_including?,
block_pattern(<<~PATTERN)
  {
    #SharedGroups.all
    #ExampleGroups.all
    #Includes.all
  }
PATTERN

#let_bang(node) ⇒ Object


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

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

#method_called?(node) ⇒ Object


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

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

#on_block(node) ⇒ Object


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

def on_block(node)
  return unless example_or_shared_group_or_including?(node)

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