-
-
Save cmaitchison/970459 to your computer and use it in GitHub Desktop.
Close postgres open connections before running test suite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
task 'db:test:prepare' => :close_postgres_connections | |
task :close_postgres_connections => :environment do | |
#Kill any other open connections on the test db | |
db_adapter = defined?(::ActiveRecord::Base) ? ActiveRecord::Base.connection : nil | |
db_adapter ||= defined?(::Sequel::Model) ? ::Sequel::Model.db : nil | |
if Rails.env.test? && db_adapter | |
db_config = Rails.configuration.database_configuration[Rails.env].symbolize_keys | |
begin | |
#Will only work on Postgres > 8.4 | |
::Sequel::Model.db.execute <<-SQL.gsub(/^\s{6}/,'') | |
SELECT COUNT(pg_terminate_backend(procpid)) | |
FROM pg_stat_activity | |
WHERE datname = '#{db_config[:database]}'; | |
SQL | |
rescue => e | |
#Will raise an error as it kills existing process running this command | |
#Seems to be only way to ensure *all* test connections are closed | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment