rubocop: Style/FormatStringToken false positive

I came across the following false positive while doing rspec-puppet testing on an sshd module. Sometimes contents of a file can include valid string tokens that look like unannotated Ruby tokens. These are usually wrapped inside a RegEx for testing.

For example, sshd_config can include %u which is a valid username reference.

Expected behavior

The following code shouldn’t be flagged as offensive:

it {
  is_expected.to contain_file('/etc/ssh/sshd_config')
    .with_content(%r{^    ChrootDirectory /var/chroot/%u$})
}

Actual behavior

RuboCop triggers Style/FormatStringToken error:

spec/classes/sshd_spec.rb:3:55: C: Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over unannotated tokens (like %s).
    .with_content(%r{^    ChrootDirectory /var/chroot/%u$})
                                                      ^^

Steps to reproduce the problem

The snippet above triggers the described offense.

RuboCop version

$ rubocop -V
0.52.0

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 20 (3 by maintainers)

Commits related to this issue

Most upvoted comments

We ran into this with strftime too.

@pegasd Thanks for your bug report! I’ll fix it.

@jeremywadsack @envygeeks The strftime’s issue will be fixed by #5230 See https://github.com/bbatsov/rubocop/issues/5223 https://github.com/bbatsov/rubocop/pull/5230

Another instance of this is the use of printf style format strings which I think are pretty common — in my experience much more common than format strings (outside of Rails I18n).

Style/FormatStringToken: Prefer annotated tokens (like %<foo>s) over unannotated tokens (like %s).
      @partition ||= dataset.table("#{table.table_id}$#{@date.strftime('%Y%m%d')}")

[Tagging #4539 for x-ref.]

@lionel218 I confirmed with that code and opened another issue for you: https://github.com/bbatsov/rubocop/issues/5630

@pocke Thanks for linking that fix for strftime — sorry I missed that when looking for previous reports.