Create my own rake test:foo task - ruby-on-rails

I have a bunch of tests that aren't unit or functional tests, they're of the format test/foo/special_test.rb
I want to create a rake task like rake test:units that will run all the tests in the foo folder. How do I do this?
Edit: I'd actually like rake test:foo to be a little different from rake test:units, in that I do not want it to run when I do simply rake test.

I don't remember where this is from, so unfortunately I can't give proper acknowledgement, but this should work. I say "should" because I've stopped using it, but grabbed it from my git history.
# First, 'reopen' the default :test namespace and create your custom task.
namespace :test do
Rake::TestTask.new(:foo_tests => ["test:prepare", "other_dependent_rake_tasks"] ) do |t|
DatabaseCleaner.strategy = :transaction # If using this.
t.libs << "test"
# Will also get subfolders within test/foo
t.test_files = FileList['test/foo/**/*_test.rb', 'test/foo/*_test.rb']
end
end
You can remove the default "test" task and redefine it so that when you run rake test it will automatically also run rake test:foo_tests.
remove_task "test"
desc 'Adding onto Rails regular tests'
task :test do
# Add all the names of tests you want run here.
errors = %w(test:units test:functionals test:integration test:foo_tests).collect do |task|
begin
puts "Running: #{task}"
Rake::Task[task].invoke
nil
rescue => e
task
end
end.compact
abort "Errors running #{errors * ', '}!" if errors.any?
end

Related

A General Method to be invoked before every rake execution

In my rails project (Rails 3.1, Ruby 1.9.3) there are around 40 rake tasks defined. The requirement is that I should be able to create an entry (the rake details) in a database table right when we start each rake. The details I need are the rake name, arguments, start time and end time. For this purpose, I don't want rake files to be updated with the code. Is it possible to do this outside the scope of rake files.
Any help would be greatly appreciated!!
Try this
https://github.com/guillermo/rake-hooks
For example in your Rakefile
require 'rake/hooks'
task :say_hello do
puts "Good Morning !"
end
before :say_hello do
puts "Hi !"
end
#For multiple tasks
namespace :greetings do
task :hola do puts "Hola!" end ;
task :bonjour do puts "Bonjour!" end ;
task :gday do puts "G'day!" end ;
end
before "greetings:hola", "greetings:bonjour", "greetings:gday" do
puts "Hello!"
end
rake greetings:hola # => "Hello! Hola!"
This seems to be a bit awkward, But it may help others.
Rake.application.top_level_tasks
will return an array of information including Rake name and its arguments.
Reference attached below.
pry(main)> a = Rake.application.top_level_tasks
=> ["import_data[client1,", "data.txt]"]
When you create rake task, you can pass a parent task which will run before your task:
task my_task: :my_parent_task do
# ...
end
If your task depends from more than 1 task, you can pass an array of parent tasks
task my_task: [:my_prev_task, :my_another_prev_task] do
# ...
end

Using Rake with Rufus

I'm trying to user rake and rufus, both of which I am new to. I want to have Rufus call my rake task but I am getting the following error. Don't know how to build task 'inbox:process_inbox'
lib/tasks/inbox_tasks.rb
namespace :inbox do
task :process_inbox do
logger = Logger.new(Rails.root.to_s + "/log/scheduler.log")
logger.info "Rufus Here!"
end
end
rufus_scheduler.rb
require 'rufus-scheduler'
require 'rake'
scheduler = Rufus::Scheduler.new
scheduler.every '10s', :first_at => Time.now + 3 do
Rake::Task["inbox:process_inbox"]
end
As #jmettraux (the creator of rufus-scheduler!) has already answered, the problem is that the rake task is defined in a .rb file instead of .rake file.
Adding some more details to help in the future.
While creating a new rake task, you could get the rails generator to automatically create the file with appropriate structure.
Example: Running
> rails g task inbox process_inbox
create lib/tasks/inbox.rake
will create a file named lib/tasks/inbox.rake with content:
namespace :inbox do
desc "TODO"
task process_inbox: :environment do
end
end
Having a DESC in the task definition is important; that allows for verifying that the rake task is defined and available, by running either rake -T inbox or rake -T | grep inbox
> rake -T inbox
rake inbox:process_inbox # TODO
Could this one help?
How to build task 'db:populate' (renaming inbox_tasks.rb to inbox_tasks.rake)
(did a simple https://www.google.com/?#q=rails+don%27t+know+how+to+build+task ...)

How to fix "uninitialized constant" in a Rake task

I have a problem when I do:
namespace :xaaron do
task :get_roles do
roles = Xaaron::Role.all
puts roles
end
task :get_role, [:name] do |t, args|
role = Xaaron::Role.find(args[:name].parameterize)
puts role
end
end
The first task will work fine. I can even add binding.pry and run Xaaron::Role and get information about Roles back. But the second task fails with:
NameError: uninitialized constant Xaaron::Role
I run each task in my main app because these tasks are inside an engine, using:
bin/rake xaaron:get_roles` and `bin/rake xaaron:get_role
I can run bin/rails c in the main application that uses the engine and run Xaaron::Role and get information about Roles table.
Why is the second one failing but the first one is not? Is there scoping with arguments?
I'm not sure why either works, but if this is Rails and those are Rails models, your tasks should depend on the environment:
task :get_roles => [ :environment ] do
By depending on the :environment task, it first loads Rails.
Also see: What's the 'environment' task in Rake?.
You can also run a Rake task as
bundle exec rake environment xaaron:get_role
This will load the Rails environment first.
I kept getting uninitialized constant errors for a Rake task, even after depending on :environment and running with bundle exec.
The issue was that I was making a Rake::TestTask and, even though the Rake task had access to all constants, the test files themselves did not have access to constants.
The solution was to add this line to the top of my test file:
require_relative '../config/environment'
This is the Rake task:
require "rake/testtask"
Rake::TestTask.new(:test) do |t|
t.libs << "test"
t.libs << "lib"
t.test_files = FileList["test/**/test_*.rb"]
end
To add, as of Ruby 1.9 and above, you can use this hash syntax:
namespace :xaaron do
desc "Rake task to get roles"
task get_roles: :environment do
roles = Xaaron::Role.all
puts roles
end
#####
end
And then you can run the command below to run the Rake task:
rake xaaron:get_roles
or
bundle exec rake xaaron:get_roles

How can I run a rake task from a delayed_job

I'd like to run a rake task (apn:notifications:deliver from the apn_on_rails gem) from a delayed_job. In other words, I'd like enqueue a delayed job which will call the apn:notifications:deliver rake task.
I found this code http://pastie.org/157390 from http://geminstallthat.wordpress.com/2008/02/25/run-rake-tasks-with-delayedjob-dj/.
I added this code as DelayedRake.rb to my lib directory:
require 'rake'
require 'fileutils'
class DelayedRake
def initialize(task, options = {})
#task = task
#options = options
end
##
# Called by Delayed::Job.
def perform
FileUtils.cd RAILS_ROOT
#rake = Rake::Application.new
Rake.application = #rake
### Load all the Rake Tasks.
Dir[ "./lib/tasks/**/*.rake" ].each { |ext| load ext }
#options.stringify_keys!.each do |key, value|
ENV[key] = value
end
begin
#rake[#task].invoke
rescue => e
RAILS_DEFAULT_LOGGER.error "[ERROR]: task \"#{#task}\" failed. #{e}"
end
end
end
Everything runs fine until the delayed_job runs and it complains:
[ERROR]: task "apn:notifications:deliver" failed. Don't know how to build task 'apn:notifications:deliver'
How do I let it know about apn_on_rails? I'd tried require 'apn_on_rails_tasks' at the top of DelayedRake which didn't do anything. I also tried changing the directory of rake tasks to ./lib/tasks/*.rake
I'm somewhat new to Ruby/Rails. This is running on 2.3.5 on heroku.
Why don't do just a system call ?
system "rake apn:notifications:deliver"
I believe it's easier if you call it as a separate process. See 5 ways to run commands from Ruby.
def perform
`rake -f #{Rails.root.join("Rakefile")} #{#task}`
end
If you want to capture any errors, you should capture STDERR as shown in the article.

How to prevent Rake test to call task db:test:prepare

Every time I want to run Rake test the task db:test:prepare is being called and it rebuilds my test environment database from schema.rb and migrations. What I would like to achive is to disable the call of db:test:prepare when I want to test make Rails application. Is it possible without modifying Rails gem?
Here's a solution I've seen around:
In your Rakefile:
Rake::TaskManager.class_eval do
def remove_task(task_name)
#tasks.delete(task_name.to_s)
end
end
In lib/tasks/db/test.rake:
Rake.application.remove_task 'db:test:prepare'
namespace :db do
namespace :test do
task :prepare do |t|
# rewrite the task to not do anything you don't want
end
end
end
There is a plugin that takes care of this for you: override_rake_task. Here is a quick usage example:
namespace :db do
namespace :test do
override_task :prepare do; end
end
end
For some older version of rails - you can place Rake::Task['db:test:prepare'].clear at the end of your Rakefile

Resources