Class: RuboCop::Cop::RSpec::Extra::BeEmpty

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

Overview

Prefer using be_empty when checking for an empty array.

Examples:

# bad
expect(array.empty?).to be true
expect(array.empty?).to be_truthy
expect(array.size).to eq(0)
expect(array.length).to eq(0)
expect(array.count).to eq(0)
expect(array).to eql([])
expect(array).to contain_exactly
expect(array).to match_array([])

# good
expect(array).to be_empty

Constant Summary collapse

MSG =
"Use `be_empty` matchers for checking an empty array."
RESTRICT_ON_SEND =
%i[be be_truthy eq eql contain_exactly match_array].freeze

Instance Method Summary collapse

Instance Method Details

#expect_array_empty_true?(node) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/rubocop/cop/rspec/extra/be_empty.rb', line 31

def_node_matcher :expect_array_empty_true?, <<~PATTERN
  (send
    (send nil? :expect $(send _ :empty?))
    #Runners.all
    ${(send nil? :be true) (send nil? :be_truthy)}
  )
PATTERN

#expect_array_matcher?(node) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/rspec/extra/be_empty.rb', line 49

def_node_matcher :expect_array_matcher?, <<~PATTERN
  (send
    (send nil? :expect _)
    #Runners.all
    ${
      (send nil? {:eq :eql :match_array} (array))
      (send nil? :contain_exactly)
    }
  )
PATTERN

#expect_array_size_zero?(node) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/rubocop/cop/rspec/extra/be_empty.rb', line 40

def_node_matcher :expect_array_size_zero?, <<~PATTERN
  (send
    (send nil? :expect $(send _ {:size :length :count}))
    #Runners.all
    $(send nil? {:eq :eql} (int 0))
  )
PATTERN

#on_send(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rubocop/cop/rspec/extra/be_empty.rb', line 60

def on_send(node)
  expect_array_empty_true?(node.parent) do |actual, expect|
    register_offense(actual, expect)
  end
  expect_array_size_zero?(node.parent) do |actual, expect|
    register_offense(actual, expect)
  end
  expect_array_matcher?(node.parent) do |expect|
    register_offense(nil, expect)
  end
end