Writing and testing a custom RuboCop cop
Tags: rails, ruby, rubocop
Published: 2022-10-21 17:36:44

Solving a problem is great — but keeping it from coming back is even better. As we resolve issues in our code base, we often consider how to keep that classification of issue out of the code base entirely. Sometimes we reach for [RuboCop](https://docs.rubocop.org/rubocop/index.html) to help us police certain patterns. This also helps to document the originating issue and educates teammates on why these patterns are undesirable.

RuboCop is more than just a linter. It is highly extensible and allows you to write [custom cops](https://thoughtbot.com/blog/rubocop-custom-cops-for-custom-needs) to enforce specific behavior. These cops can be used to create better code practices, prevent bad patterns from sneaking into a legacy code base, and provide training for other engineers. But it can be tricky to know [how to create a new cop](https://docs.rubocop.org/rubocop/development.html) and if it will work long-term.

> We can write unit tests to ensure the success of our custom cops, just as we would with any application code.
Let's explore this with an example to show how testing could be done.

## Testing custom cops

With the Aha! engineering team, every model has an `account_id` attribute present and for [security reasons][security], we never want this to be set via mass-assignment. To avoid this, we want to prevent certain attributes from being added to [attr_accessible][attr_accessible].

[attr_accessible]: https://apidock.com/rails/ActiveRecord/Base/attr_accessible/class

[security]: https://brakemanscanner.org/docs/warning_types/mass_assignment/

```ruby
# bad
class Foo
  attr_accessible :name, :account_id
end
Foo.create(account_id: 1, name: "foo")
# good
class Foo
  attr_accessible :name
end
foo = Foo.new(name: "foo")
foo.account_id = 1
foo.save
```

We have a custom cop that analyzes the arguments to that method and will error if any protected attribute is present. The custom cop we have ends up looking something like this:

```ruby
class RuboCop::Cop::ProtectedAttrAccessibleFields < RuboCop::Cop::Cop
  # We can define a list of attributes we want to protect
  PROTECTED_ATTRIBUTES = [
    :account_id,
  ].freeze
  # We can define an error message that is displayed when an offense is detected.
  # This can be helpful to communicate information back to other engineers
  ERROR_MESSAGE = <<~ERROR.freeze
    Only permit attributes that are safe to be completely user controlled. Typically any *_id field could be problematic.
    Instead perform direct assignment of the field after doing a scoped lookup. This is the safest way to handle user input.
    Some fields such as #{PROTECTED_ATTRIBUTES.inspect} should never be used as part of attr_accessible.
  ERROR
  # We want to examine method calls. Particularly those that are calling the attr_accessible method
  # and also have arguments we care about
  def on_send(node)
    if receiver_attr_accessible?(node) && protected_arguments?(node)
      # If we do detect an attr_accessible call with arguments we care about, we can record an offense
      add_offense(node, message: ERROR_MESSAGE)
    end
  end
  private
  def receiver_attr_accessible?(node)
    node.method_name == :attr_accessible
  end
  def protected_arguments?(node)
    node.arguments.any? do |argument|
      if argument.sym_type? || argument.str_type?
        PROTECTED_ATTRIBUTES.include?(argument.value.to_sym)
      end
    end
  end
end
```

This custom cop does the trick. Adding a test for it ensures that it won't break in the future when we update RuboCop or extend the functionality. In order to write a test, we need to understand how the custom cops are set up and run.

## Instantiate a custom cop

`RuboCop::Cop::Cop` inherits from `RuboCop::Cop::Base` and that allows the instantiation without [any arguments](https://github.com/rubocop/rubocop/blob/d8c2cd0d891c9e49f528041d3b0758a6fa480265/lib/rubocop/cop/base.rb#L71). So it turns out this isn't anything special — creating a new instance of our cop is really as simple as: `RuboCop::Cop::ProtectedAttrAccessibleFields.new`

If the cop requires some kind of configuration, it can be passed to the instance via a `RuboCop::Config` object. The `RuboCop::Config` takes two arguments. RuboCop can [provide configuration](https://docs.rubocop.org/rubocop/configuration.html) via YML files. You can use the first argument of `RuboCop::Config` to pass this configuration with various values from the test. The second argument is the path of the loaded YML file, which can be ignored in the tests.

```ruby
config = RuboCop::Config.new({ RuboCop::Cop::ProtectedAttrAccessibleFields.badge.to_s => {} }, "/")
cop = RuboCop::Cop::ProtectedAttrAccessibleFields.new(config)
```

## Process, execute, examine

As it turns out, there is a [method](https://github.com/rubocop/rubocop/blob/d8c2cd0d891c9e49f528041d3b0758a6fa480265/lib/rubocop/cop/base.rb#L238) available, `RuboCop::Cop::Base#parse` , that accepts a string as input and will return something the cop can process.

This allows us to have something like:

```ruby
source = <<~CODE
  attr_accessible :account_id
CODE
processed_source = cop.parse(source)
```

There is a class from within RuboCop, `RuboCop::Cop::Commissioner` , that is responsible for taking a [list of cops](https://github.com/rubocop/rubocop/blob/d8c2cd0d891c9e49f528041d3b0758a6fa480265/lib/rubocop/cop/commissioner.rb#L44) and using those to [investigate](https://github.com/rubocop/rubocop/blob/d8c2cd0d891c9e49f528041d3b0758a6fa480265/lib/rubocop/cop/commissioner.rb#L79) the processed source code. In order to run our cop, we can run this method.

```ruby
commissioner = RuboCop::Cop::Commissioner.new([cop])
investigation_report = commissioner.investigate(processed_source)
```

The `RuboCop::Cop::Commissioner#investigate` method will return an instance of [RuboCop::Cop::Commissioner::InvestigationReport](https://github.com/rubocop/rubocop/blob/d8c2cd0d891c9e49f528041d3b0758a6fa480265/lib/rubocop/cop/commissioner.rb#L18) which is a simple struct class that has a list of offenses that have been recorded.

## Put it all together

We end up with a test file that looks something like this:

```ruby
describe RuboCop::Cop::ProtectedAttrAccessibleFields do
  let(:config) { RuboCop::Config.new({ described_class.badge.to_s => {} }, "/") }
  let(:cop) { described_class.new(config) }
  let(:commissioner) { RuboCop::Cop::Commissioner.new([cop]) }
  it "records an offense if we use allow account_id as a string" do
    source = <<~CODE
      attr_accessible :foo, 'account_id'
    CODE
    investigation_report = commissioner.investigate(cop.parse(source))
    expect(investigation_report.offenses).to_not be_blank
    expect(investigation_report.offenses.first.message).to eql described_class::ERROR_MESSAGE
  end
  it "records an offense if we use allow account_id as symbol" do
    source = <<~CODE
      attr_accessible :foo, :account_id
    CODE
    investigation_report = commissioner.investigate(cop.parse(source))
    expect(investigation_report.offenses).to_not be_blank
    expect(investigation_report.offenses.first.message).to eql described_class::ERROR_MESSAGE
  end
  it "doesn't record an offense if no protected attribute is used" do
    source = <<~CODE
      attr_accessible :foo
    CODE
    investigation_report = commissioner.investigate(cop.parse(source))
    expect(investigation_report.offenses).to be_blank
  end
end
```

Now that we know how to write tests, we can use them as a starting point for building new cops, extending existing cops, and ensuring that things continue to function as our application grows and evolves. These little investments into [project-specific cops](https://evilmartians.com/chronicles/custom-cops-for-rubocop-an-emergency-service-for-your-codebase) can end up being a large investment in the future health of the projects.

**Sign up for a free trial of Aha! Develop**

Aha! Develop is a fully extendable agile development tool. Prioritize the backlog, estimate work, and plan sprints. If you are interested in an integrated [product development](https://www.aha.io/suite-overview) approach, use [Aha! Roadmaps and Aha! Develop together](https://www.aha.io/product/overviewhttps://www.aha.io/product/integrations/develop). Sign up for a [free 30-day trial](https://www.aha.io/trial) or [join a live demo](https://www.aha.io/live-demo) to see why more than 5,000 companies trust our software to build lovable products and be happy doing it.