Spyros
Spyros

Reputation: 48626

Executing the db:seed task for development

I have the following task:

namespace :db do
  desc "Drop, create, migrate, seed the database and prepare the test database for rspec"
  task :reset_db => :environment do
    puts "Environment Check: Rails Environment = #{Rails.env}"
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:migrate'].invoke
    #Rake::Task['db:fixtures:load'].invoke
    Rake::Task['db:test:prepare'].invoke
    puts 'Seeding Database..'
    Rake::Task['db:seed'].invoke
  end
end

This task works fine up to the last db:seed line.
It seems to be using the test environment and creates the data there, while all the other tasks execute in the development environment. When I execute rake db:seed via the command line, it runs correctly in the development environment.

How can I prevent it from running in the test environment?

Upvotes: 4

Views: 2769

Answers (2)

fakeleft
fakeleft

Reputation: 2900

Redefine your seed task as follows:

namespace :db do
  task :seed => :environment do
    env_seed_file = File.join(Rails.root, 'db', 'seeds', "#{Rails.env}.rb")
    load(env_seed_file) if File.exist?(env_seed_file)
  end
end

Now you can do stuff like this (the env-specific file is loaded after the regular seeds file):

db
+-- seeds
|   +-- development.rb
|   +-- production.rb
|   +-- staging.rb
+-- seeds.rb

Credit: codeofficer.com

Upvotes: 0

Frost
Frost

Reputation: 11957

The db:test:prepare rake task prepares the test database, and therefore sets RAILS_ENV=test.

So the reason why your task gets run in the testing environment is because db:test:prepare actually overwrites your RAILS_ENV variable.

Upvotes: 3

Related Questions