在rspec中测试数据库连接

时间:2013-01-16 14:24:25

标签: ruby-on-rails-3 rspec resque

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

 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

1 个答案:

答案 0 :(得分:3)

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

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