Database configuration using rspec-Rails

Asked

Viewed 115 times

0

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 executing rspec I have 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)

You weren’t supposed to create the database?

If I put system('rake db:create') works, but it’s good practice to do it?

1 answer

1


There is a rake task to prepare the test bench:

bundle exec rake db:test:prepare

This command creates the database, runs migrations and loads the schema. From there you can run the test suite.

  • How can I do this automatically when the test suite runs?

  • added system('rake db:test:prepare') in my spec/rails_helper.Rb

  • If you run the test suite with the command rake spec rather than directly with rspec this task will also be round before the execution of the tests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.