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

#eq_type_with_identity?(node) ⇒ Object


30
31
32
# File 'lib/rubocop/cop/rspec/be_eq.rb', line 30

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

#on_send(node) ⇒ Object


34
35
36
37
38
39
40
# File 'lib/rubocop/cop/rspec/be_eq.rb', line 34

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