我是使用mixins的新手,我更熟悉基於Java的依賴注入。如何在Rails中正確使用模擬功能進行測試?
比方說,我用一個mixin模塊爲一類提供數據庫連接,如在http://fabiokung.com/2010/05/06/ruby-and-dependency-injection-in-a-dynamic-world/描述:
module ConnectionProvider
def connection
# open a database connection and return it
end
end
# reopening the class to mix the module in
class Repository
include ConnectionProvider
end
這讓我做到這一點:
class Repository
def find(id)
connection.execute("SELECT ...")
end
end
現在我也不必須通過Repository初始值設定項來傳遞ConnectionProvider對象。
假設我想使用模擬版本的ConnectionProvider進行測試,所以我想將MockConnectionProvider包含在Repository中而不是ConnectionProvider中。 ConnectionProvider和MockConnectionProvider都提供了方法連接。這是我認爲這應該完成的方式。
對於我的正常的Rails應用
在environment.rb中:
require File.dirname(__FILE__) + "/../lib/repository"
對於我的測試腳本
在我的測試文件:
require File.dirname(__FILE__) + "/../lib/repository_mocked"
這是正確的嗎?如果沒有,有人可以提供一篇文章的鏈接,展示正確的方法嗎?