Search code examples
ruby-on-railstestingrakefixtures

Changing a rake task to work on test environment


  namespace :fixtures do
    namespace :load do 
      task :prepare => :environment do
        ENV['FIXTURES_PATH'] = "spec/fixtures"
        ENV['RAILS_ENV'] ||= "test"
        puts ENV.inspect
        Rake::Task["db:fixtures:load"].invoke
      end
    end
  end

I have added this to a special.rake file in ./lib/tasks in order to cause the rake db:fixtures:load command to apply to fixtures in the spec/fixtures directory, and to apply to the test environment.

It's not working. Where have I gone wrong?


Solution

  • You need to reconnect to the database. Something like

    ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["test"])
    

    Changing ENV['RAILS_ENV'] after environment is already loaded doesn't do anything.

    Perhaps it would also work if you load the environment task after you change ENV, but not sure about that:

      task :prepare do
        ENV['RAILS_ENV'] ||= "test"
        Rake::Task["environment"].invoke
        Rake::Task["db:fixtures:load"].invoke
      end