Class: Rubocop::Cop::RSpec::UselessDynamicDefinition

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

Overview

Flags useless dynamic hook/let definitions via ‘.each`, `.each_key`, or `.each_value` without defining a wrapping `context` explicitly inside the loop block. Without it, the let definition will always/only be set to the final value.

Examples:


# bad
context 'foo' do
  [true, false].each do |bool|
    before do
      stub_something(bool: bool)
    end

    let(:foo) { build(:model, bool: bool) }

    it 'works' do
      # `bool` is always `false`
    end
  end
end

# good
context 'foo' do
  [true, false].each do |bool|
    context "with bool #{bool}" do # <--
      before do
        stub_something(bool: bool)
      end

      let(:foo) { build(:model, bool: bool) }

      it 'works' do
        # `bool` is `true` and then `false`
      end
    end
  end
end

Constant Summary collapse

MSG =
'Avoid useless dynamic definitions without `context`.'
RESTRICT_ON_SEND =
%i[each each_key each_value].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



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

def on_send(node)
  return unless dynamic_definition?(node.parent)

  add_offense(node.loc.selector)
end