0

我已经设置了一个查询从数据库而不是主数据库的 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
4

1 回答 1

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
于 2013-01-16T19:40:51.410 回答