I have to migrate some data and I'd like to test some models that use a different connection, i.e. other than one defined in database.yml
develoment
, test
groups.
So I added a new database connection to database.yml
:
default: &default
adapter: postgresql
encoding: unicode
user: postgres
password:
pool: 5
development:
<<: *default
database: myapp_development
host: <%= ENV['DATABASE_HOST'] %>
test:
<<: *default
database: myapp_test
host: <%= ENV['DATABASE_HOST'] %>
production:
<<: *default
host: <%= ENV['DATABASE_HOST'] %>
database: myapp_production
username: <%= ENV['DATABASE_USER'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
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']%>
Next, I creates a base model class in lib/mystore_migration
folder:
module MystoreMigration
class MystoreModel < ApplicationRecord
self.abstract_class = true
establish_connection(:mystore)
end
end
Other model classes used by the rake task inherit the above MystoreMigration
class.
Next, when I just tried to initialize one of the models that use mystore
connection in RSpec test file:
MystoreMigration::ShopInfo.new(
address: Faker::Address.street_address,
address2: Faker::Address.street_name,
...
)
and run it, it failed:
OCIError:
ORA-12162: TNS:net service name is incorrectly specified
It seems like RSpec tried to use another settings/database or whatever instead of the one I defined with establish_connection(:mystore)
.
If I add unless Rails.env.test?
condition to establish_connection
:
module MystoreMigration
class MystoreModel < ApplicationRecord
self.abstract_class = true
establish_connection(:mystore) unless Rails.env.test?
end
end
the error message is different and says it can'd set up relations:
ActiveRecord::StatementInvalid:
PG::UndefinedTable: ERROR: relation "STORE_INFO" does not exist
LINE 8: WHERE a.attrelid = '"STORE_INFO"'::regclass
As you see, in the first case, it tried to connect to Oracle database what is correct but it failed. In the second case it tried to connect to Postgresql database (wrong, as it is used in other environments than mystore
).
If I run a rake task that uses mystore
connection, it works, - running tests- fails. What's wrong with that ?
I'm using Rails 5.2.0
, ruby 2.5.0
, macOS.
Thank you.
unless Rails.env.test?
atestablish_connection
! – Iata