Testing database connection in rspec

偶尔善良 提交于 2019-12-04 06:22:27

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/14360562/testing-database-connection-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!