Can I whitelist a RuboCop Rails/DynamicFindBy method on a per-file basis

RuboCop's Rails/DynamicFindBy cop gives false positives when it encounters Capybara's (as opposed to Rail's) find_by_id method.
There's apparently a way to whitelist methods so that they are ignored by this cop. See http://rubocop.readthedocs.io/en/latest/cops_rails/#railsdynamicfindby (mentioning Whitelist attribute).

I would like to whitelist find_by_id, but only for certain files (the ones with Capybara tests) in my tests/integration directory. Is this possible?

(I am aware that I can turn off the entire cop on a file by file basis, but I don't want to turn off the cop entirely. I am also aware that I can turn off the cop for portions of a file, or on a line-by-line basis, but those are not preferred solutions.)

3 answers

  • answered 2017-08-16 19:31 Thomas Walpole

    You should be able to set this in your rubocop config file like

    # In .rubocop.yml
    Rails/DynamicFindBy:
      Include:
        - tests/integrations/**/*.rb
      Whitelist:
        - find_by_id
        - find_by_something_else
    

    Or you could add a new .rubocop.yml file to the directory that contains the files in which you want the methods whitelisted and inherit from the overall config - see https://github.com/bbatsov/rubocop/blob/master/manual/configuration.md#inheritance

  • answered 2017-08-16 19:31 user2069311

    That answer is almost it, and can be easily modified to do exactly what I want. The answer isn't perfect, because it's directory-by-directory, rather than file-by-file. So the only change is to list specific files in the Include:

    # In .rubocop.yml
    Rails/DynamicFindBy:
      Include:
        - tests/integrations/first_test.rb
        - tests/integrations/second_test.rb
      Whitelist:
        - find_by_id
       - find_by_something_else
    

  • answered 2017-08-16 19:31 Drenmi

    There is no way to do this on a file-by-file basis. Closest you can get is having a particular configuration on a directory level, by putting another .rubocop.yml configuration file inside.

    It might look like this is a solution at first:

    # .rubocop.yml
    Rails/DynamicFindBy:
      Include:
        - tests/integrations/first_test.rb
        - tests/integrations/second_test.rb
      Whitelist:
        - find_by_id
    

    But Include means "included for inspection", not "included for configuration", so this actually excludes all other project files from being inspected by the cop entirely. (Which you wouldn't notice if there were no offences in the other files to begin with.)

    That leaves two options:

    1. Whitelist #find_by_id for all files in /integrations, using another configuration file.
    2. Use inline disables and -enables.

    The former would probably be the recommended one, unless there's a strong reason for why #find_by_id should not be allowed in the other integration tests.