具有多个数据库的 Rails RSpec [英] Rails RSpec with Multiple Databases

查看:26
本文介绍了具有多个数据库的 Rails RSpec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行一个 Rails 应用程序,我们正在将我们的注册过程拆分为一个单独的应用程序.注册应用程序有自己独立的数据库(用于 CMS 和收集潜在客户),但它也需要访问主数据库.这使用 ActiveRecord::Base.establish_connection 非常有效.

I run a Rails app, and we're in the process of splitting out our signup process to a separate app. The signup app has its own separate database (for CMS and collecting prospects), but it also needs to have access to the main database. This works really well using ActiveRecord::Base.establish_connection.

但是,我希望能够编写一些规范.问题是,我如何编写规范/测试而不在每次测试运行时清除我的开发数据库?如果我以测试模式进入控制台,很明显测试模式已从我的主应用程序挂接到开发数据库中.

However, I'd like to be able to write some specs. The trouble is, how can I write specs/tests without clearing out my development database every time my tests run? If I go into the console in test mode, it's obvious the the test mode is hooked into the development database from my main app.

这是我的 database.yml 文件的样子:

Here's what my database.yml file looks like:

development: 
  database: signup_dev

test:
  database: signup_test

main_app_dev: 
  database: main_app_dev

main_app_test: 
  database: main_app_test

基于这个文件,我希望establish_connection在开发模式下连接到数据库my_app_dev,在测试模式下my_app_test模式.有什么想法吗?

Based on this file, I'd like establish_connection to connect to connect to the database my_app_dev in development mode, and my_app_test in test mode. Any ideas?

推荐答案

我们有一个 gem,它基本上是连接到我们遗留系统的 ActiveRecord 模型的集合.在我们的例子中,所有这些模型都包含在一个模块中,所有与旧数据库相关的模型都从该模块连接.

We have a gem that is basically a collection of ActiveRecord models that connect to our legacy system. In our case we have all those models contained in a module from which all models related to the legacy database connects.

module Legacy
  class Base < ActiveRecord::Base
    establish_connection :legacy
  end

  class User < Base
  end
end

通过此设置,可以非常轻松地切换数据库连接.如果您真的要进行自动检测,则可以在基类中放置逻辑以确定要使用的数据库:

With this setup it makes it really easy to switch out the database connection. If you really go for that automated detection you can put logic in your base class to determine which database to use:

module Legacy
  class Base < ActiveRecord::Base
    if Rails.env == 'test'
      establish_connection :legacy_test
    else
      establish_connection :legacy
   end
end

或者简单地告诉你的模块在你的规范助手中使用哪个连接:

Or simply tell your module which connection to use in your spec helper:

# spec/spec_helper.rb    
Legacy::Base.establish_connection(ActiveRecord::Base.configurations['legacy_test'])

我个人推荐第二个选项.当然,这两种解决方案都依赖于命名空间模型.

Personally I would recommend the second option. Of course both solutions depend on namespaced models.

对等

这篇关于具有多个数据库的 Rails RSpec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆