0

I'm trying to test some models in a gem using Rspec and Postgres. Currently trying to do this by running a rake task in the spec_helper.rb file that will establish the pg database connection for the duration of my Rspec tests.

I've scanned other questions (my approach is largely based on these two questions 1, 2) and haven't discovered a good solution.

I'm not using the sqlite in-memory db feature due to the way our code is written.

Custom spec_helper looks like this:

RSpec.configure do |config|
  load "support/schema.rb"
  load File.expand_path("../../../lib/tasks/database.rake", __FILE__)
  require File.dirname(__FILE__) + 'support/models.rb'
  Rake::Task['database'].invoke

However when I run rspec it tells me that there is no connection pool:

active_record/connection_adapters/abstract/connection_pool.rb:570:in
`retrieve_connection': No connection pool for ActiveRecord::Base
(ActiveRecord::ConnectionNotEstablished)

Does anyone have any advice or insight on this issue? It would be much appreciated.

Community
  • 1
  • 1
DHG
  • 23
  • 5

1 Answers1

0

You should establish database connection:

ActiveRecord::Base.establish_connection(adapter: 'postgresql', 
  encoding: 'unicode', database: '<db_name>', username: '<user>')

This should run before any others database interactions (including loading schema.rb)

Oleksandr Avoiants
  • 1,889
  • 17
  • 24
  • here is my database task in rake: `desc "Establishes postgresql connection"` `task :database do` ` ActiveRecord::Base.establish_connection(` ` adapter: 'postgresql',` ` host: 'tmp',` ` database: 'user',` ` username: 'user',` ` password: '',` ` port: 5432,` ` )` ` end` – DHG Oct 26 '16 at 14:27
  • I think you should `load "support/schema.rb"` after establishing database connection – Oleksandr Avoiants Oct 26 '16 at 14:29
  • 1
    this solved the error - there are still a few issues with connecting to the db, but it seems the connection had to be established before loading the files. thanks! – DHG Oct 26 '16 at 14:35