rspec_base = File.expand_path(File.dirname(__FILE__) + '/../../rspec/lib')
$LOAD_PATH.unshift(rspec_base) if File.exist?(rspec_base)
require 'spec/rake/spectask'
require 'spec/translator'

$TASK_NAMES = []

def prepare_for_test sub
ActiveRecord::Base.establish_connection(:development)
db_specs = ActiveRecord::Base.configurations[env_name_for(sub)]
ActiveRecord::Base.connection.recreate_database(db_specs['database'])
ActiveRecord::Base.establish_connection(env_name_for(sub))
ActiveRecord::Schema.verbose = true
`rake db:schema:load`
end

def env_name_for sub
"#{sub}_test"
end

def spec_task_name for_sub
"#{for_sub}:parallel_spec"
end

[:models, :controllers, :views, :helpers, :lib].each do |sub|
$TASK_NAMES << sub
Spec::Rake::SpecTask.new(spec_task_name(sub)) do |t|
t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
end
end

task :foo => "db:schema:dump" do
env_dir = File.join(RAILS_ROOT, 'config', 'environments')
$TASK_NAMES.each do |task|
FileUtils.ln_s(File.join(env_dir, "test.rb"), File.join(env_dir, "#{task}_test.rb"), :force => true)
fork do
RAILS_ENV = ENV['RAILS_ENV'] = env_name_for(task)
prepare_for_test task
Rake::Task[spec_task_name(task)].invoke
FileUtils.rm_rf(File.join(env_dir, "#{task}_test.rb"))
end
end
end