Rspec - 未初始化的常数RAILS_ENV

时间:2015-07-10 17:00:29

标签: ruby-on-rails ruby rspec

我运行我的任务包db:restore并显示错误:

** Execute db:restore
rake aborted!
NameError: uninitialized constant RAILS_ENV
/home/dima/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/gems/rspec-core-2.5.2/lib/rspec/core/backward_compatibility.rb:20:in `const_missing'
/home/dima/myapp/bdsmgalaxy/lib/tasks/mysql.rake:24:in `block (2 levels) in <top (required)>'

我的任务是:

require 'yaml'

namespace :db do
    def backup_prep
    @directory = File.join(RAILS_ROOT, 'db', 'backup')
    @db = YAML::load( File.open( File.join(RAILS_ROOT, 'config', 'database.yml') ) )[ RAILS_ENV ]
    @db_params = "-u #{@db['username']} #{@db['database']}"
    @db_params = "-p#{@db['password']} #{@db_params}" unless @db['password'].blank?
  end

  desc 'Backup database by mysqldump'
  task :backup => :environment do
    backup_prep
    FileUtils.mkdir @directory unless File.exists?(@directory)
    file = File.join( @directory, "#{RAILS_ENV}_#{DateTime.now.to_s}.sql" )
    command = "mysqldump #{@db_params} | gzip > #{file}.gz" #--opt --skip-add-locks 
    puts "dumping to #{file}..."
    # p command
    exec command
  end

  desc "restore most recent mysqldump (from db/backup/*.sql.*) into the current environment's database."
  task :restore => :environment do
    unless RAILS_ENV=='development'      
      puts "Are you sure you want to import into #{RAILS_ENV}?! [y/N]"
      return unless STDIN.gets =~ /^y/i
    end
    backup_prep
    wildcard  = File.join( @directory, ENV['FILE'] || "#{ENV['FROM']}*.sql*" )
    puts file = `ls -t #{wildcard} | head -1`.chomp  # default to file, or most recent ENV['FROM'] or just plain most recent
    if file =~ /\.gz(ip)?$/
      command = "gunzip < #{file} | mysql #{@db_params}"
    else
      command = "mysql #{@db_params} < #{file}"
    end
    p command
    puts "please wait, this may take a minute or two..."
    exec command
  end
end

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

RAILS_ENV是一个环境变量。您必须使用ENV['RAILS_ENV']

即:

unless ENV['RAILS_ENV']=='development'