uninitialized constant Rake::TestTask - ruby-on-rails

I am trying to run bundle exec rake redmine:plugins NAME=redmine_checklists RAILS_ENV=production and getting this error
NameError: uninitialized constant Rake::TestTask /usr/share/redmine/lib/tasks/redmine.rake:163:in
`block (3 levels) in <top (required)>' /usr/share/redmine/lib/tasks/redmine.rake:161:in `block (2
levels) in <top (required)>' /usr/share/redmine/lib/tasks/redmine.rake:117:in `block in <top
(required)>' /usr/share/redmine/lib/tasks/redmine.rake:18:in `<top (required)>'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `block in run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `each'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:660:in `run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/application.rb:518:in `run_tasks_blocks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/engine.rb:459:in `load_tasks'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/railtie.rb:190:in `public_send'
/var/lib/gems/2.5.0/gems/railties-6.0.3.2/lib/rails/railtie.rb:190:in `method_missing'
/usr/share/redmine/Rakefile:6:in `<top (required)>' /var/lib/gems/2.5.0/gems/rake-
13.0.1/exe/rake:27:in `<top (required)>' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:63:in `load' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:63:in `kernel_load' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli/exec.rb:28:in `run' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/cli.rb:476:in `exec' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/vendor/thor/lib/thor/invocation.rb:127:in `invoke_command'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/vendor/thor/lib/thor.rb:399:in `dispatch'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/cli.rb:30:in `dispatch'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/vendor/thor/lib/thor/base.rb:476:in `start'
/var/lib/gems/2.5.0/gems/bundler-2.1.4/lib/bundler/cli.rb:24:in `start'
/var/lib/gems/2.5.0/gems/bundler-
2.1.4/exe/bundle:46:in `block in <top (required)>' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/lib/bundler/friendly_errors.rb:123:in `with_friendly_errors' /var/lib/gems/2.5.0/gems/bundler-
2.1.4/exe/bundle:34:in `<top (required)>' /usr/local/bin/bundle:23:in `load'
/usr/local/bin/bundle:23:in
`<main>' (See full trace by running task with --trace)
My /usr/share/redmine/lib/tasks/redmine.rake
namespace :redmine do
namespace :attachments do
desc 'Removes uploaded files left unattached after one day.'
task :prune => :environment do
Attachment.prune
end
desc 'Moves attachments stored at the root of the file directory (ie. created before Redmine 2.3) to their subdirectories'
task :move_to_subdirectories => :environment do
Attachment.move_from_root_to_target_directory
end
desc 'Updates attachment digests to SHA256'
task :update_digests => :environment do
Attachment.update_digests_to_sha256
end
end
namespace :tokens do
desc 'Removes expired tokens.'
task :prune => :environment do
Token.destroy_expired
end
end
namespace :watchers do
desc 'Removes watchers from what they can no longer view.'
task :prune => :environment do
Watcher.prune
end
end
desc 'Fetch changesets from the repositories'
task :fetch_changesets => :environment do
Repository.fetch_changesets
end
desc 'Migrates and copies plugins assets.'
task :plugins do
Rake::Task["redmine:plugins:migrate"].invoke
Rake::Task["redmine:plugins:assets"].invoke
end
desc <<-DESC
FOR EXPERIMENTAL USE ONLY, Moves Redmine data from production database to the development database.
This task should only be used when you need to move data from one DBMS to a different one (eg. MySQL to PostgreSQL).
WARNING: All data in the development database is deleted.
DESC
task :migrate_dbms => :environment do
ActiveRecord::Base.establish_connection :development
target_tables = ActiveRecord::Base.connection.tables
ActiveRecord::Base.remove_connection
ActiveRecord::Base.establish_connection :production
tables = ActiveRecord::Base.connection.tables.sort - %w(schema_migrations plugin_schema_info)
if (tables - target_tables).any?
list = (tables - target_tables).map {|table| "* #{table}"}.join("\n")
abort "The following table(s) are missing from the target database:\n#{list}"
end
tables.each do |table_name|
Source = Class.new(ActiveRecord::Base)
Target = Class.new(ActiveRecord::Base)
Target.establish_connection(:development)
[Source, Target].each do |klass|
klass.table_name = table_name
klass.reset_column_information
klass.inheritance_column = "foo"
klass.record_timestamps = false
end
Target.primary_key = (Target.column_names.include?("id") ? "id" : nil)
source_count = Source.count
puts "Migrating %6d records from #{table_name}..." % source_count
Target.delete_all
offset = 0
while (objects = Source.offset(offset).limit(5000).order("1,2").to_a) && objects.any?
offset += objects.size
Target.transaction do
objects.each do |object|
new_object = Target.new(object.attributes)
new_object.id = object.id if Target.primary_key
new_object.save(:validate => false)
end
end
end
Target.connection.reset_pk_sequence!(table_name) if Target.primary_key
target_count = Target.count
abort "Some records were not migrated" unless source_count == target_count
Object.send(:remove_const, :Target)
Object.send(:remove_const, :Source)
end
end
namespace :plugins do
desc 'Migrates installed plugins.'
task :migrate => :environment do
name = ENV['NAME']
version = nil
version_string = ENV['VERSION']
if version_string
if version_string =~ /^\d+$/
version = version_string.to_i
if name.nil?
abort "The VERSION argument requires a plugin NAME."
end
else
abort "Invalid VERSION #{version_string} given."
end
end
begin
Redmine::Plugin.migrate(name, version)
rescue Redmine::PluginNotFound
abort "Plugin #{name} was not found."
end
Rake::Task["db:schema:dump"].invoke
end
desc 'Copies plugins assets into the public directory.'
task :assets => :environment do
name = ENV['NAME']
begin
Redmine::Plugin.mirror_assets(name)
rescue Redmine::PluginNotFound
abort "Plugin #{name} was not found."
end
end
desc 'Runs the plugins tests.'
task :test do
Rake::Task["redmine:plugins:test:units"].invoke
Rake::Task["redmine:plugins:test:functionals"].invoke
Rake::Task["redmine:plugins:test:integration"].invoke
end
namespace :test do
desc 'Runs the plugins unit tests.'
Rake::TestTask.new :units => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/unit/**/*_test.rb"
end
desc 'Runs the plugins functional tests.'
Rake::TestTask.new :functionals => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/functional/**/*_test.rb"
end
desc 'Runs the plugins integration tests.'
Rake::TestTask.new :integration => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/integration/**/*_test.rb"
end
desc 'Runs the plugins ui tests.'
Rake::TestTask.new :ui => "db:test:prepare" do |t|
t.libs << "test"
t.verbose = true
t.pattern = "plugins/#{ENV['NAME'] || '*'}/test/ui/**/*_test.rb"
end
end
end
end
# Load plugins' rake tasks
Dir[File.join(Rails.root, "plugins/*/lib/tasks/**/*.rake")].sort.each { |ext| load ext }
Rails -v
6.0.3.2
Ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]
gem list rake
rake (13.0.1, 12.3.1)
I have tried to remove Rake::TestTask from redmine.rake but it caused more errors. I am not good at ruby-on-rails and I am just trying to install a redmine plugin.

You need to require "rake/testtask" add this in rake file in order to use Rake::TestTask
Refer article Creating a test rake task

Related

Rails Tenant schema switching with background jobs not working

Setting up a scheduled rake task using Whenever gem.
Required to switch to a specific schema (Using Apartment gem in my project)
Code in config/schedule.rb
env :PATH, ENV['PATH']
env :GEM_PATH, ENV['GEM_PATH']
set :output, "#{Whenever.path}/log/scheduler.log"
every 1.minute do
rake "db:my_task"
end
Code in lib/tasks/my_task.rake
namespace :db do
task :my_task => :environment do
Apartment::Tenant.switch("subdomain") do
#My Code here
end
end
end
Produces the following error in logs log/scheduler.logs
rake aborted!
Apartment::TenantNotFound: One of the following schema(s) is invalid: "subdomain" "public"
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:72:in `rescue in connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:65:in `connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:91:in `block in switch!'
/var/lib/gems/2.3.0/gems/activesupport-5.1.3/lib/active_support/callbacks.rb:97:in `run_callbacks'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:88:in `switch!'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:105:in `switch'
/home/user1/Desktop/SPERICORN/kidversity/lib/tasks/dynamic_age_setter.rake:4:in `block (2 levels) in <top (required)>'
/var/lib/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
ActiveRecord::StatementInvalid: Could not find schema kochi
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/postgresql_adapter.rb:66:in `connect_to_new'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:91:in `block in switch!'
/var/lib/gems/2.3.0/gems/activesupport-5.1.3/lib/active_support/callbacks.rb:97:in `run_callbacks'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:88:in `switch!'
/var/lib/gems/2.3.0/gems/apartment-1.2.0/lib/apartment/adapters/abstract_adapter.rb:105:in `switch'
/home/user1/Desktop/SPERICORN/kidversity/lib/tasks/dynamic_age_setter.rake:4:in `block (2 levels) in <top (required)>'
/var/lib/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
Tasks: TOP => db:dynamic_age_setter
(See full trace by running task with --trace)
you are missing ActiveRecord::Base.establish_connection.connection try this
sample code below :
namespace :debtor_email_data_fix do
desc 'update data'
task email_normalize_to_downcase: :environment do
create_connection_with_db
Apartment::Tenant.switch!('app')
Email.find_each do |t|
t.update(address: t.address.downcase)
end
end
task all: [:email_normalize_to_downcase] do
end
private
def create_connection_with_db
ActiveRecord::Base.establish_connection.connection
end
end

Rails populate db rake task OpenURI::HTTPError: 500 Internal Server Error

I am trying to make rake task to populate db from JSON API fixer.io,
but when i type my rake :
rake db:populate
this error occurs:
OpenURI::HTTPError: 500 Internal Server Error
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:16:in `block (5 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:13:in `block (4 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:12:in `block (3 levels) in <top (required)>'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `each'
/home/jakub/Documents/workspace/exch/lib/tasks/populate.rake:11:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:populate
(See full trace by running task with --trace)
This is my rake task (populate.rake) in lib/tasks:
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
n = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys.count
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
end
end
end
end
end
Please help me, I have no idea what causes this problem.
the main problem is here, you are not taking keys of "rates"
currencies = JSON.load(open('http://api.fixer.io/latest')).keys
currencies = JSON.load(open('http://api.fixer.io/latest'))["rates"].keys
require 'open-uri'
namespace :db do
desc "Erase and fill database"
task :populate => :environment do
require 'populator'
[ConversionRate].each(&:delete_all)
latest_data = JSON.load(open('http://api.fixer.io/latest'))
currencies = latest_data["rates"].keys
n = currencies.count
currencies.each do |curr1|
currencies.each do |curr2|
ConversionRate.populate 1 do |cr|
#take care of any error, as we are going to call third party api here
begin
cr.currency1 = curr1
cr.currency2 = curr2
cr.conversion_rate = JSON.load(open('http://api.fixer.io/latest?base=' + curr1))["rates"][curr2]
rescue => e
puts "error #{e}"
end
end
end
#give a bit rest
sleep 2
end
end
end

NoMethodError: undefined method in routes_with_grape

I am trying to set up a rails grape api with the below structure.
app
api
api
V1
user.rb
app.rb
I am getting this error when i run routes_with_grape
rake aborted!
NoMethodError: undefined method `ast' for "/api/ping(.json)":String
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/actionpack-4.2.1/lib/action_dispatch/journey/path/pattern.rb:14:in `initialize'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:9:in `new'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:9:in `block (3 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:8:in `each'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:8:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:6:in `each'
/usr/local/rvm/gems/ruby-1.9.3-p551/gems/grape-rails-routes-1.0/lib/rails/tasks/routes_with_grape.rake:6:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => routes_with_grape
(See full trace by running task with --trace)
here is my code
user.rb
module V1
class User < Grape::API
desc 'Returns pong.'
get :ping do
{ ping: params[:pong] || 'pong' }
end
end
end
app.rb
class API < Grape::API
prefix 'api'
format :json
mount ::V1::User
end
Thanks!
Ditch that gem and use this code (copied from here):
namespace :grape do
desc "Grape API Routes"
task :routes => :environment do
mapped_prefix = '/api' # where mounted API in routes.rb
params_str = ' params:'
desc_limit = 45
route_info = API.routes.map {|r| [r, r.instance_variable_get(:#options)] }
max_desc_size = route_info.map{|_,info| (info[:description] || '')[0..desc_limit].size }.max
max_method_size = route_info.map{|_,info| info[:method].size }.max
max_version_size = route_info.map{|_,info| info[:version].size }.max
max_path_size = route_info.map{|_,info| info[:path].sub(':version', info[:version]).size }.max
max_params_digits = route_info.map{|_,info| info[:params].size.to_s.size }.max
format_str = format(
'%%%ds %%%ds %%%ds %%%ds%%-%ds | %%%ds%%%ds %%s',
max_desc_size + 1,
max_version_size,
max_method_size,
mapped_prefix.size,
max_path_size,
max_params_digits,
params_str.size)
route_info.each do |_,info|
fields = [
info[:description] ? info[:description][0..desc_limit] : '',
info[:version],
info[:method],
mapped_prefix,
info[:path].sub(':version', info[:version]),
info[:params].size.to_s,
params_str,
info[:params].first.inspect,
]
puts format(format_str, *fields)
info[:params].drop(1).each do |param|
puts format(format_str, *([''] * (fields.size-1)) + [param.inspect])
end
end
end
end
paste it into Rakefile and modify:
route_info = API.routes.map
with your API mounting point in my case:
under app/api/web/api.rb I have
module Web
class API < Grape::API
prefix 'api'
mount Web::V1::Root
# mount API::V2::Root (next version)
end
end
So I replaced API.routes by Web::API.routes

Import old database into new schema in Rails

I want to import my old database to new schema in rails.
For that i have .rake file:
# /lib/tasks/project_name.rake:
namespace :project_name do
require Rails.root + "lib/tasks/importer"
desc "Import old database, usage: rake project_name:import['old_database_name']"
task :import, :oldDatabase, needs::environment do |t, args|
args.with_defaults(oldDatabase: "import")
oldDatabaseName = args.oldDatabse
newDatabaseName = YAML::load(IO.read(Rails.root.join("config/database.yml")))[Rails.env]["database"]
importer = Importer.new newDatabaseName, oldDatabaseName
importer.execute
end
end
but after adding that file I can't even use any rake command.
Here is some lines of trace:
no implicit conversion of pathname into string
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:2:in `block in <top (required)>'
/Users/user/Desktop/rails/dis/lib/tasks/project_name.rake:1:in `<top (required)>'
I am doing it by looking at this tutorial:
http://www.frick-web.at/blog/import-old-database-in-new-schema-with-mysql-and-rails
try
require Rails.root.join("lib/tasks/importer").to_s

rake aborted! for uninitialized constant that does exist

I have built a rake task --
# SET RAKE TASK NAMESPACE
namespace :db do
# RAKE TASK DESCRIPTION
desc "Fetch property information and insert it into the database"
# RAKE TASK NAME
task :insert_properties do
# REQUIRE LIBRARIES
require 'nokogiri'
require 'open-uri'
# OPEN THE XML FILE
mits_feed = File.open("app/assets/xml/mits.xml")
# OUTPUT THE XML DOCUMENT
doc = Nokogiri::XML(mits_feed)
# FIND PROPERTIES OWNED BY NORTHSTEPPE AND CYCLE THORUGH THEM
doc.xpath("//Property/PropertyID/Identification[#OrganizationName='northsteppe']").each do |property|
# GATHER EACH PROPERTY'S INFORMATION
information = {
"street_address" => property.xpath("/Address/AddressLine1/text()"),
"city" => property.xpath("/Address/City/text()"),
"zipcode" => property.xpath("/Address/PostalCode/text()"),
"short_description" => property.xpath("/Information/ShortDescription/text()"),
"long_description" => property.xpath("Information/LongDescription/text()"),
"rent" => property.xpath("/Information/Rents/StandardRent/text()"),
"application_fee" => property.xpath("/Fee/ApplicationFee/text()"),
"bedrooms" => property.xpath("/Floorplan/Room[#RoomType='Bedroom']/Count/text()"),
"bathrooms" => property.xpath("/Floorplan/Room[#RoomType='Bathroom']/Count/text()"),
"bathrooms" => property.xpath("/ILS_Unit/Availability/VacancyClass/text()")
}
# CREATE NEW PROPERTY WITH INFORMATION HASH CREATED ABOVE
Property.create!(information)
end # ENDS XPATH EACH LOOP
end # ENDS INSERT_PROPERTIES RAKE TASK
end # ENDS NAMESAPCE DECLARATION
when I run "rake db:insert_properties" this is the error I produce --
rake aborted!
uninitialized constant Property
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:39:in `block (3 levels) in <top (required)>'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:237:in `block in each'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `upto'
/Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1/lib/nokogiri/xml/node_set.rb:236:in `each'
/Users/stevejobs/Sites/nsrosu/lib/tasks/property_information.rake:21:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:insert_properties
(See full trace by running task with --trace)
I have a Property model with a table set up to accept all of these attributes, so why am I getting this error?
Your rake task needs to boot the Rails environment prior to running. That way you can access the classes.
To do this, you need to run the environment task. To make this happen, change your task definition to
task :insert_properties => :environment do

Resources