Class: RuboCop::Cop::RSpec::ConditionalInLet

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

Overview

Forbids conditional logic (‘if`/`case`) inside a `let`/`let!` block. Branching object setup belongs in separate `context` blocks, not in a single `let`. Ternaries are allowed.

Examples:

# bad
let(:user) do
  if admin?
    create(:user, :admin)
  else
    create(:user)
  end
end

# good — one context each
context 'when admin' do
  let(:user) { create(:user, :admin) }
end

Constant Summary collapse

MSG =
'Do not put conditional logic in a `let` — use separate contexts.'
LET_METHODS =
%i[let let!].freeze

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object Also known as: on_numblock, on_itblock



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rubocop/cop/rspec/conditional_in_let.rb', line 32

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

  body = node.body
  return unless body

  body.each_node(:if, :case) do |conditional|
    next if conditional.if_type? && conditional.ternary?

    add_offense(conditional.loc.keyword)
  end
end