在 rspec 中测试数据库连接 [英] Testing database connection in rspec

查看:80
本文介绍了在 rspec 中测试数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个查询从数据库而不是主数据库的 resque 后台作业.在我的 resque 类中,我添加了代码来建立与从站的连接,然后在方法结束时取消建立连接.我的问题是如何在 rspec 中测试查询是否在方法中访问特定数据库?下面的代码示例:

I have setup a resque background job that queries the slave database instead of the master. In my resque class I have added code to establish a connection to the slave and then I de-establish the connection at the end of the method. My question is how would I test in rspec that a query is hitting a specific database within a method? Code sample below:

 class ResqueJob
  @queue = :resque_job

def self.perform(user_id)
  ActiveRecord::Base.establish_connection(
      :adapter  => "mysql2",
      :host     => "slave_database.com",
      :username => "test",
      :database => "sample"
    )
    user = User.find_by_id(current_user_id)
    #bunch of code in here

  ActiveRecord::Base.clear_active_connections! # Disconnect from slave database
 end

end

推荐答案

作为一般规则,您不应该测试库代码的行为.一旦您设置了连接,就由 ActiveRecord 将查询发送到正确的数据库.相反,测试您的代码是否完成了它的工作:

As a general rule, you shouldn't test behavior of library code. Once you've set the connection, it's up to ActiveRecord to send queries to the right database. Instead, test that your code does its part of the job:

it "sets the database connection to the slave" do
  params = { 
      :adapter  => "mysql2",
      :host     => "slave_database.com",
      :username => "test",
      :database => "sample"
  }
  ActiveRecord::Base.should_receive(:establish_connection).with(params)
  ActiveRecord::Base.should_receive(:clear_active_connections!)
  ResqueJob.perform(user)
end

这篇关于在 rspec 中测试数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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