In my spec / rails_helper.rb I added the following code so that the database was automatically created when running rspec :
def database_exists?
ActiveRecord::Base.connection rescue ActiveRecord::NoDatabaseError ? false : true
end
unless database_exists?
ActiveRecord::Base.establish_connection(:"#{ENV['RAILS_ENV']}")
db_config = ActiveRecord::Base.configurations[ENV['RAILS_ENV']]
ActiveRecord::Base.connection.create_database db_config
end
But when I run rspec I get the following error:
.rbenv / versions / 2.2.1 / lib / ruby / gems / 2.2.0 / gems / activerecord-4.2.1 / lib / active_record / connection_adapters / mysql2_adapter.rb: 23: in 'rescue in mysql2_connection': Unknown database 'my-db-test' (ActiveRecord :: NoDatabaseError)
Could not create the database?
If I put system('rake db:create')
works, but is it good practice to do this?