2013-01-16 127 views
0

我已經設置了查詢從屬數據庫而不是主服務器的重新創建後臺作業。在我的resque類中,我添加了代碼來建立到從站的連接,然後在方法結束時取消建立連接。我的問題是,我將如何在rspec中測試某個查詢是否在方法內擊中特定數據庫?下面的代碼示例:在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 

回答

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