我设置了一个查询从数据库而不是主数据库的救援后台作业。在我的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
作为一般规则,您不应该测试库代码的行为。一旦设置了连接,就由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