Rspec Using Development Database
The reason your tests hit the development database is because you have defined ENV['DATABASE_URL']
somewhere in your environment.
There are two ways of specifying the database connection to be used:
- Specifying the
ENV['DATABASE_URL']
- Using the very popular
database.yml
file
In many cases the first one takes prescedence over the latter.
I realized I had a problem similar to yous after using ENV['DATABASE_URL'] to set my production database, only to find out that all my environments (test & development) suddenly had started to use my production database regardless of content in database.yml
.
To solve my problem all I did was change the name on the environment variable to something else, so that it no longer overwrite my database.yml
configurations.
Reading this will solve your problem: Connection Preference information
It sounds as though somewhere in your environment (maybe one of your gems) it is setting your environment to dev or establishing a connection to your dev database.
To explicitly make it connect to the test database, add:
ActiveRecord::Base.establish_connection
to your rails_helper.
Prime candidate for troublemaker would be `gem 'rails-erd', '~> 1.4.1'. If you have this as auto-generating the diagram on migrate, when the test schema is migrated, it will connect to the dev database to dump a diagram.
Try removing this gem or perhaps the '.rake' file and see what happens.
Your rails_helper
looks strange. The first line says:
Rails.env = 'test'
At the first line you don't have Rails loaded yet (I suppose you run RSpec using bundle exec rspec
). So it should raise an error.
Therefore I made a small change in rails_helper
:
require File.expand_path('../../config/environment', __FILE__)Rails.env = 'test'require 'spec_helper'require 'rspec/rails'Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }# the rest
Now putting
expect(ActiveRecord::Base.connection_config[:database]).to match(/test/)
somewhere in your spec, should pass successfully.