Class: RuboCop::Cop::RSpec::BeEql

Inherits:
RuboCop::Cop show all
Includes:
ConfigurableEnforcedStyle, RSpec::SpecOnly
Defined in:
lib/rubocop/cop/rspec/be_eql.rb

Overview

Check for expectations where be(...) can replace eql(...).

The be matcher compares by identity while the eql matcher compares using eql?. Integers, floats, booleans, and symbols can be compared by identity and therefore the be matcher is preferable as it is a more strict test.

This cop only looks for instances of expect(...).to eql(...). We do not check to_not or not_to since !eql? is more strict than !equal?. We also do not try to flag eq because if a == b, and b is comparable by identity, a is still not necessarily the same type as b since the #== operator can coerce objects for comparison.

Examples:


# bad
expect(foo).to eql(1)
expect(foo).to eql(1.0)
expect(foo).to eql(true)
expect(foo).to eql(false)
expect(foo).to eql(:bar)

# good
expect(foo).to be(1)
expect(foo).to be(1.0)
expect(foo).to be(true)
expect(foo).to be(false)
expect(foo).to be(:bar)

Constant Summary collapse

MSG =
'Prefer `be` over `eql`'.freeze

Constants included from RSpec::SpecOnly

RSpec::SpecOnly::DEFAULT_CONFIGURATION

Instance Method Summary collapse

Methods included from RSpec::SpecOnly

#relevant_file?

Instance Method Details

#autocorrect(node) ⇒ Object



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

def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.loc.selector, 'be')
  end
end

#on_send(node) ⇒ Object



44
45
46
47
48
# File 'lib/rubocop/cop/rspec/be_eql.rb', line 44

def on_send(node)
  eql_type_with_identity(node) do |eql|
    add_offense(eql, :selector, MSG)
  end
end