简体   繁体   English

使用ActiveRecord在Rails中测试具有多个数据库连接的模型

[英]Testing models with multiple database connections in Rails using ActiveRecord

What is the best way to test a model that is using a different database connection in Rails. 测试在Rails中使用不同数据库连接的模型的最佳方法是什么? For example I have a model FooBar that is read only: 例如,我有一个只读的模型FooBar:

class FooBar < ActiveRecord::Base
  establish_connection configurations['foo_bars']
  # ...
end

Are there any good conventions, hacks, or plugins out there? 那里有什么好的约定,黑客或插件吗?

In my experience, once the connection is established you can treat the model just like any other model. 根据我的经验,一旦建立连接,您就可以像处理任何其他模型一样对待模型。 Since you are just consuming the data that will simplify some of the testing as you wont need to test for data validations. 由于您只是在使用简化某些测试的数据,因为您不需要测试数据验证。

Obviously because Rails is talking to two different databases from two different models, you won't be able to do joins between the databases and so there will be nothing to test there either. 显然因为Rails正在与来自两个不同模型的两个不同的数据库进行通信,所以您将无法在数据库之间进行连接,因此也无法在那里进行测试。

So, to answer the question: what is the best way to test a model that is using a second database? 那么,回答这个问题:测试使用第二个数据库的模型的最佳方法是什么? I would say, exactly the same way that you would test it if it was your only database. 我会说,如果它是你唯一的数据库,那么你将测试它的方式完全相同。

I find that in my models that wrap my legacy databases I have to add some special tie in code that makes things a little more "Rails-y" and makes the view and controller code look like there are has_one and belongs_to type code in there. 我发现在我的模型中包装我的遗留数据库时,我必须在代码中添加一些特殊的联系,使事情变得更加“Rails-y”,并使视图和控制器代码看起来像has_onebelongs_to类型代码。 I do have tests that exercise those custom methods. 我确实有运行这些自定义方法的测试。

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM