我必须迁移一些数据,并且我想测试一些使用不同连接的模型,即除database.yml
develoment
,test
组中定义的连接以外的其他模型。
因此,我向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']%>
接下来,我在lib/mystore_migration
文件夹中创建一个基础模型类:
module MystoreMigration
class MystoreModel < ApplicationRecord
self.abstract_class = true
establish_connection(:mystore)
end
end
rake任务使用的其他模型类继承了上面的MystoreMigration
类。
接下来,当我尝试初始化RSpec测试文件中使用mystore
连接的模型之一时:
MystoreMigration::ShopInfo.new(
address: Faker::Address.street_address,
address2: Faker::Address.street_name,
...
)
并运行它,它失败了:
OCIError:
ORA-12162: TNS:net service name is incorrectly specified
RSpec似乎尝试使用其他设置/数据库或其他任何方式代替我用establish_connection(:mystore)
定义的设置/数据库。
如果我将unless Rails.env.test?
条件添加到establish_connection
:
module MystoreMigration
class MystoreModel < ApplicationRecord
self.abstract_class = true
establish_connection(:mystore) unless Rails.env.test?
end
end
错误消息有所不同,并说它可以建立关系:
ActiveRecord::StatementInvalid:
PG::UndefinedTable: ERROR: relation "STORE_INFO" does not exist
LINE 8: WHERE a.attrelid = '"STORE_INFO"'::regclass
如您所见,在第一种情况下,它尝试将正确的连接到Oracle数据库,但是失败了。在第二种情况下,它尝试连接到Postgresql数据库(错误,因为它在mystore
以外的其他环境中使用)。
如果我运行使用mystore
连接的rake任务,则可以正常运行-运行测试-失败。那怎么了
我正在使用Rails 5.2.0
,ruby 2.5.0
,macOS。
谢谢。
答案 0 :(得分:0)
运行测试时,Rails似乎将查询test
中database.yml
组中定义的数据库-在我的情况下是myapp_test
。但是,在使用mystore
连接查询模型时,将找不到对应的表,因为在test
环境中没有为那些模型定义数据库连接。这意味着唯一的解决方案是模拟使用mystore
连接的模型的所有数据库请求。