Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test database not using .env values

I am running tests using rails test:models and got this error (though the tests still run)

ActiveRecord::NoDatabaseError: We could not find your database: postgres. Which can be found in the database configuration file located at config/database.yml.

A database called postgres does not exist because I gave the DB's a different name.

My database.yml is :

# config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  username: <%= ENV['POSTGRES_USER'] %>
  password: <%= ENV['POSTGRES_PASSWORD'] %>
  pool: 5
  timeout: 5000
  host: <%= ENV['POSTGRES_HOST'] %>
development:
  <<: *default
  database: <%= ENV['POSTGRES_DB'] %>
test:
  <<: *default
  database: <%= ENV['POSTGRES_TEST_DB'] %>
production:
  <<: *default
  database: <%= ENV['POSTGRES_DB'] %>

and my respective .env is :

# ./env
POSTGRES_USER='bob'
# If you declared a password when creating the database:
POSTGRES_HOST='localhost'
POSTGRES_DB='database1'
POSTGRES_TEST_DB='database1_test'

In PSQL, you can also see the test database isn't using the .env value for its owner but the production database is :

                      List of databases
     Name     |     Owner     | Encoding | Collate | Ctype |        Access privileges        
--------------+---------------+----------+---------+-------+---------------------------------
 database1      | bob          | UTF8     | C       | C     | 
 database1_test | bobsurname | UTF8     | C       | C     | 
like image 624
nc14 Avatar asked Mar 04 '26 17:03

nc14


2 Answers

The issue might be that your ENV variables aren't available in your test suite.

To check this try accessing them in a console:

> RAILS_ENV=test rails console
> ENV # should print out all your ENV variables 
> ENV['POSTGRES_TEST_DB'] # should print out the name of your test db

If I'm right and these ENV vars aren't available when your environment is test, you'll need to look at a strategy to include the ENV vars you need.

  • ThoughtBot has a few ideas that are pretty solid
  • You can add ENV vars manually as this SO from way back points out
like image 114
Chiperific Avatar answered Mar 06 '26 05:03

Chiperific


I think you don't have the database database1_test You can login to Postgres via:

  1. sudo -u postgres psql to login into Postgres
  2. \l will show the all database

If database1_test doesn't exist, run this cmd to create and migrate database for testing

RAILS_ENV=test rails db:prepare
like image 42
Lee Drum Avatar answered Mar 06 '26 06:03

Lee Drum