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

查看:263
本文介绍了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?

推荐答案

我们有一个宝石,基本上是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天全站免登陆