简体   繁体   中英

Rails - Rake test and rubocop in one task

I'm trying to setup my rails project so that all the verification required by a contributor is in one command, currently we have been running:

rake test

But now we also want to use rubocop for static analysis:

rubocop -R -a

I want this to be executable in one simple rake task. It would be nice to override 'rake test' to run rubocop then the standard rake test stuff for a rails project, as then no-one will have to remember to change the command. But if I have to create a separate rake task, that's probably fine too.

I've seen the rubocop rake integration here, at the bottom , but I'm not sure how to bundle that with 'rake test' into one task... Any thoughts?

I prefer to set my default task to run rubocop then the tests. Either way, it is a good idea to have those tasks separate rather than have one task do two things.

require 'rubocop/rake_task'

task :default => [:rubocop, :test]

desc 'Run tests'
task(:test) do
  # run your specs here
end

desc 'Run rubocop'
task :rubocop do
  RuboCop::RakeTask.new
end

Your tasks:

> rake -T
rake rubocop  # Run rubocop
rake test     # Run tests

This is the .rake file that I ended up with in the end.

desc 'Run tests and rubocop'
task :validate do
  Rake::Task['rubocop'].invoke
  Rake::Task['test'].invoke
end

task :rubocop do
  require 'rubocop'
  cli = Rubocop::CLI.new
  cli.run(%w(--rails --auto-correct))
end

You could easily define your own rake task which first invokes Rails' test rake task and then the code snippet you mentioned for rubocop.

For example, in a .rake file you could have something like that:

require 'rubocop/rake_task'

desc 'Run tests and rubocop'
task :my_test do
  Rake::Task['test'].invoke
  RuboCop::RakeTask.new  
end

If you feel the need to customize the call to Rubocop and that involves more code, you could create another custom task, say :rubocop, which you then invoke from :my_test as well.

Finally, an alternative to creating your own rake task and sticking with rake test would be to modify your test_helper to invoke whatever you need invoked after testing is completed.

It appears to have changed from:

Rubocop::RakeTask.new

to:

Rubo op::RakeTask.new op::RakeTask.new

See ma? I know how to CamelCase!

I used following .rake file to run the test and rubocop tasks at once:

task default: %w[rubocop test]

RuboCop::RakeTask.new(:rubocop) do |task|
  task.patterns = ['**/*.rb']
  task.fail_on_error = false
  task.options = ["--auto-correct-all"]
end

task :test do
  ruby 'test/program_test.rb'
end

The first line allows both tasks to be run by calling rake .

Command line arguments can also be added in the options array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM