Search code examples
rubocop

How to define exceptions to rubocop rules?


We are using this setting to require space before code blocks

Layout/SpaceBeforeBlockBraces:
  EnforcedStyle: space

However, in RSpec examples, we do not use the space after expect and change methods when they use blocks for readability:

expect{ calling_the_method }.to change{ Model.all.size }.by(1)

Rubocop complains about the code above. Is it possible to tell it to ignore blocks after specific methods or ignore lines matching regex?

I have tried:

Layout/SpaceBeforeBlockBraces:
  EnforcedStyle: space
  IgnoredPatterns: ['\A\s*((?:expect)|(.*change))']

Solution

  • Is it possible to tell it [the SpaceBeforeBlockBraces cop] to ignore blocks after specific methods or ignore lines matching regex?

    No. As of 2018-08-12, I don't think that SpaceBeforeBlockBraces supports the IgnoredPattern option, but it might be an easy PR. The IgnoredPattern option is a mixin (rubocop/cop/mixin/ignored_pattern.rb) so you could just include it into whatever cop you want. Rubocop has strict rules for contributions, so if you do a PR, make sure to read all instructions thoroughly.

    The SpaceBeforeBlockBraces cop should support the Exclude option, if you want to exclude your test directory. I think all cops support Include and Exclude.