establish_connection(:other_database) in model is still called in tests

63 views
Skip to first unread message

belgoros

unread,
Jun 29, 2018, 5:25:42 AM6/29/18
to Ruby on Rails: Talk
I have to establish connection to a database different than defined for development environment.
Here is how I added the specific connection to database.yml:

default:
...


development
:
...


test
:
....


mystore
:
  adapter
: oracle_enhanced
  host
: <%= ENV['mystore_db_host']%>
  port
: <%= ENV['mystore_db_port']%>
  database
: <%= ENV['mystore_db_name']%>
  username
: <%= ENV['mystore_db_user']%>
  password
: <%= ENV['mystore_db_password']%>

So I create a base model class as follows:

module MystoreMigration
 
class MystoreModel < ApplicationRecord
    establish_connection
(:mystore) unless Rails.env.test?
 
end
end

Than I have some model defined that inherit the above class, for example:

module MystoreMigration
 
class StoreInfo < MystoreModel
...
 
end
end

It works fine in development environment but when running tests and mocking the above models, Rails is still trying to establish the connection.
To make it work, I had to add the same environment variables to test section in Figaro gem application.yml file:

development:
  mystore_db_host
: "XXXX"
  mystore_db_port
: "XXXX"
  mystore_db_name
: "XXXX"
  mystore_db_user
: "XXXX"
  mystore_db_password
: "XXXX"


....
test
:
  mystore_db_host
: "XXXX"
  mystore_db_port
: "XXXX"
  mystore_db_name
: "XXXX"
  mystore_db_user
: "XXXX"
  mystore_db_password
: "XXXX"

If I remove the variables from test environment, the following simple test where I mock the model class as follows:

RSpec.describe MystoreMigration::StoreMigrator do


  let
(:shop) { build(:shop) }
  let
(:store) { double(MystoreMigration::StoreInfo)}
  let
(:store_migrator) { MystoreMigration::StoreMigrator.new([store]) }


  describe
'initialization' do
    it
'should have stores initialized' do
      expect
(store_migrator.stores).not_to be_empty
   
end
 
end

Class under test (just to chesk the constructor):

module MystoreMigration
 
class StoreMigrator


 
def initialize(stores = [])
     
@stores = stores
   
end
...


 fails with error:

OCIError:

       ORA-12162: TNS:net service name is incorrectly specified

     # oci8.c:561:in oci8lib_250.bundle

     # /Users/Serguei/.rvm/gems/ruby-2.5.0/gems/ruby-oci8-2.2.5.1/lib/oci8/oci8.rb:142:in `initialize'


What's wrong with that ? Thank you.
Reply all
Reply to author
Forward
0 new messages