|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +RSpec.describe RuboCop::Cop::Performance::StringBytesize, :config do |
| 4 | + let(:msg) { 'Use `String#bytesize` instead of calculating the size of the bytes array.' } |
| 5 | + |
| 6 | + it 'registers an offense with `size` method' do |
| 7 | + expect_offense(<<~RUBY) |
| 8 | + string.bytes.size |
| 9 | + ^^^^^^^^^^ #{msg} |
| 10 | + RUBY |
| 11 | + |
| 12 | + expect_correction(<<~RUBY) |
| 13 | + string.bytesize |
| 14 | + RUBY |
| 15 | + end |
| 16 | + |
| 17 | + it 'registers an offense with `length` method' do |
| 18 | + expect_offense(<<~RUBY) |
| 19 | + string.bytes.length |
| 20 | + ^^^^^^^^^^^^ #{msg} |
| 21 | + RUBY |
| 22 | + |
| 23 | + expect_correction(<<~RUBY) |
| 24 | + string.bytesize |
| 25 | + RUBY |
| 26 | + end |
| 27 | + |
| 28 | + it 'registers an offense with `count` method' do |
| 29 | + expect_offense(<<~RUBY) |
| 30 | + string.bytes.count |
| 31 | + ^^^^^^^^^^^ #{msg} |
| 32 | + RUBY |
| 33 | + |
| 34 | + expect_correction(<<~RUBY) |
| 35 | + string.bytesize |
| 36 | + RUBY |
| 37 | + end |
| 38 | + |
| 39 | + it 'registers an offense with string literal' do |
| 40 | + expect_offense(<<~RUBY) |
| 41 | + "foobar".bytes.count |
| 42 | + ^^^^^^^^^^^ #{msg} |
| 43 | + RUBY |
| 44 | + |
| 45 | + expect_correction(<<~RUBY) |
| 46 | + "foobar".bytesize |
| 47 | + RUBY |
| 48 | + end |
| 49 | + |
| 50 | + it 'registers an offense and autocorrects with safe navigation' do |
| 51 | + expect_offense(<<~RUBY) |
| 52 | + string&.bytes&.count |
| 53 | + ^^^^^^^^^^^^ #{msg} |
| 54 | + RUBY |
| 55 | + |
| 56 | + expect_correction(<<~RUBY) |
| 57 | + string&.bytesize |
| 58 | + RUBY |
| 59 | + end |
| 60 | + |
| 61 | + it 'registers an offense and autocorrects with partial safe navigation' do |
| 62 | + expect_offense(<<~RUBY) |
| 63 | + string&.bytes.count |
| 64 | + ^^^^^^^^^^^ #{msg} |
| 65 | + RUBY |
| 66 | + |
| 67 | + expect_correction(<<~RUBY) |
| 68 | + string&.bytesize |
| 69 | + RUBY |
| 70 | + end |
| 71 | + |
| 72 | + it 'does not register an offense without array size method' do |
| 73 | + expect_no_offenses(<<~RUBY) |
| 74 | + string.bytes |
| 75 | + RUBY |
| 76 | + end |
| 77 | + |
| 78 | + it 'does not register an offense with `bytes` without explicit receiver' do |
| 79 | + expect_no_offenses(<<~RUBY) |
| 80 | + bytes.size |
| 81 | + RUBY |
| 82 | + end |
| 83 | + |
| 84 | + it 'does not register an offense when the receiver is of type `int`' do |
| 85 | + expect_no_offenses(<<~RUBY) |
| 86 | + 3.bytes.size |
| 87 | + RUBY |
| 88 | + end |
| 89 | +end |
0 commit comments