Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate rubocop with Rake?

rubocop is a code style checker for Ruby. A similar tool to rubocop, Cane, can be integrated with Rake. I prefer rubocop to Cane since rubocop makes checks based on the Ruby Style Guide and it seems to spot more problems. To automate the process of style checking I would like to integrate rubocop with Rake so that the build fails if code quality is lacking.

Gem already supports adding tests to packages via Rake. I would like to do the same with style checks so that style checks are run along with the tests. How can I do this?

If it helps to start with a Rakefile here is one:

# -*- coding: utf-8; mode: ruby -*-

require 'bundler/gem_tasks'
require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs << 'test'
  t.test_files = FileList['test/unit/test*.rb']
end

desc 'Run tests'
task default: :test
like image 889
N.N. Avatar asked Feb 21 '13 17:02

N.N.


4 Answers

As of version 0.10.0 rubocop contain a custom rake task that you can use. Just put the following in your Rakefile

require 'rubocop/rake_task'

RuboCop::RakeTask.new

Make sure to use upper-case 'R' and 'C' or you will get a NameError.

like image 169
Martin Avatar answered Nov 18 '22 05:11

Martin


I highly recommend,

require 'rubocop/rake_task'

RuboCop::RakeTask.new(:rubocop) do |t|
  t.options = ['--display-cop-names']
end

This uses the rubocop's own rake tasks and allows you to pass options if you like.

like image 33
HParker Avatar answered Nov 18 '22 05:11

HParker


You will probably find https://github.com/yujinakayama/guard-rubocop useful if you use Guard for your RSpec tests. It enables Rubocop to give you instant feedback as soon as you save the file, along with your test results.

like image 3
Joe Gatt Avatar answered Nov 18 '22 07:11

Joe Gatt


I needed to do something similar myself, and ended up looking in the internal source code of the RuboCop::RakeTask here:

https://github.com/rubocop/rubocop/blob/a34a1c2c2dd1fa6d90ffd06c183421a495a0717c/lib/rubocop/rake_task.rb#L40-L43

      require 'rubocop'

      cli = CLI.new
      puts 'Running RuboCop...' if verbose
      result = cli.run(options)
      abort('RuboCop failed!') if result.nonzero? && fail_on_error

You can actually invoke similar code directly in your own codebase / rake task.

I ended up writing a little wrapper module I can call to, with some default flags that I always want to be applied:

module RubocopCli
  def self.run!(*args)
    require "rubocop"
    cli = RuboCop::CLI.new
    result = cli.run(["--display-cop-names", "--force-exclusion", "--fail-level", "autocorrect", *args])
    raise "RubocopCli.run! Linting failed." if result.nonzero?
  end
end

Then you can call it with additional args from any task, or app code, like:

files_to_lint = %w[lib/whatever.rb spec/lib/whatever_spec.rb]
RubocopCli.run!("--auto-correct", *files_to_lint)
like image 1
animatedgif Avatar answered Nov 18 '22 05:11

animatedgif