I develop Sinatra application and use there ActiveRecord for working with database, but I encountered one problem. I wrote a test for a model and it breaks with
SQLite3::CantOpenException: unable to open database file
Connection to database is established in test_helper.rb with the following code:
Dir.chdir('..') do
ActiveRecord::Base.establish_connection(db_config)
end
and ActiveRecord::Base.connected?
get false. If I call User.find(:all)
for example after connection establishment test will pass and ActiveRecord::Base.connected?
will be true. Why? I don't understand.
ActiveRecord::Base.establish_connection
only sets up the connection and ActiveRecord does not actually connect until a connection to the database is requested.
The following code may help you force ActiveRecord to establish a connection for the connection-pool:
connected = ActiveRecord::Base.connection_pool.with_connection { |con| con.active? } rescue false
The rescue false
hides a couple of potential exceptions (eg. PG::ConnectionBad
).
Refer to the documentation of :with_connection for more information.
ActiveRecord::Base.establish_connection is delegated to ActiveRecord::ConnectionAdapters::ConnectionHandler#stablish_connection and if you take a look at its implementation you'll see that it just creates a connection pull
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With