Class: RuboCop::Cop::RSpec::BeEq

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rspec/be_eq.rb

Overview

Check for expectations where ‘be(…)` can replace `eq(…)`.

The ‘be` matcher compares by identity while the `eq` matcher compares using `==`. Booleans and nil can be compared by identity and therefore the `be` matcher is preferable as it is a more strict test.

Examples:

# bad
expect(foo).to eq(true)
expect(foo).to eq(false)
expect(foo).to eq(nil)

# good
expect(foo).to be(true)
expect(foo).to be(false)
expect(foo).to be(nil)

Constant Summary collapse

MSG =
'Prefer `be` over `eq`.'
RESTRICT_ON_SEND =
%i[eq].freeze

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

#eq_type_with_identity?(node) ⇒ Object



33
34
35
# File 'lib/rubocop/cop/rspec/be_eq.rb', line 33

def_node_matcher :eq_type_with_identity?, <<~PATTERN
  (send nil? :eq {true false nil})
PATTERN

#on_send(node) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/rubocop/cop/rspec/be_eq.rb', line 37

def on_send(node)
  return unless eq_type_with_identity?(node)

  add_offense(node.loc.selector) do |corrector|
    corrector.replace(node.loc.selector, 'be')
  end
end