blob: 6242c7a4c5e199b59cb83d8688fea6cdc7250906 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
# frozen_string_literal: true
require 'fast_spec_helper'
require 'rubocop'
require_relative '../../../../rubocop/cop/performance/ar_count_each.rb'
RSpec.describe RuboCop::Cop::Performance::ARCountEach do
include CopHelper
subject(:cop) { described_class.new }
context 'when it is not haml file' do
it 'does not flag it as an offense' do
expect(subject).to receive(:in_haml_file?).with(anything).at_least(:once).and_return(false)
expect_no_offenses <<~SOURCE
show(@users.count)
@users.each { |user| display(user) }
SOURCE
end
end
context 'when it is haml file' do
before do
expect(subject).to receive(:in_haml_file?).with(anything).at_least(:once).and_return(true)
end
context 'when the same object uses count and each' do
it 'flags it as an offense' do
expect_offense <<~SOURCE
show(@users.count)
^^^^^^^^^^^^ If @users is AR relation, avoid `@users.count ...; @users.each... `, this will trigger two queries. Use `@users.load.size ...; @users.each... ` instead. If @users is an array, try to use @users.size.
@users.each { |user| display(user) }
SOURCE
expect(cop.offenses.map(&:cop_name)).to contain_exactly('Performance/ARCountEach')
end
end
context 'when different object uses count and each' do
it 'does not flag it as an offense' do
expect_no_offenses <<~SOURCE
show(@emails.count)
@users.each { |user| display(user) }
SOURCE
end
end
context 'when just using count without each' do
it 'does not flag it as an offense' do
expect_no_offenses '@users.count'
end
end
context 'when just using each without count' do
it 'does not flag it as an offense' do
expect_no_offenses '@users.each { |user| display(user) }'
end
end
end
end
|