问题
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