skip to Main Content

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     | 

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search