0
我是新來的st /嘲弄。如何殘段或模擬第三方庫
如何從外部庫中存根方法,以便我只能測試我的模塊的方法,而無需實際調用庫?
此外,我想知道,是我寫這個模塊的方法去或違反編程的一些重要原則嗎?
# file_module.rb
module FileModule
require 'net/ftp'
@ftp = nil
def self.login
if [email protected] || @ftp.closed?
@ftp = Net::FTP.new(Rails.configuration.nielsen_ftp_server)
@ftp.login(Rails.configuration.nielsen_ftp_user, Rails.configuration.nielsen_ftp_password)
end
end
def self.get_list_of_files_in_directory(directory, type)
login
@ftp.chdir("/#{directory}")
files = case type
when "all" then @ftp.nlst("*")
when "add" then @ftp.nlst("*add*")
end
end
end
# file_module_spec.rb (RSpec)
require 'spec_helper'
describe NielsenFileModule do
describe ".get_list_of_files_in_directory" do
it "returns correct files for type all" do
# how to mock Net::FTP or stub all its methods so I simulate the return value of @ftp.nlst("*")?
NielsenFileModule.get_list_of_files_in_directory("test_folder", "all").count.should eq 6
end
end
end
@ gmacdokugall的方法是一個很好的方法,但代碼中存在一個可能導致沮喪的隱患:在file_module.rb中的第6行賦予的@ ftp變量不相同@在實例方法中被引用的ftp變量。 '@ ftp'被賦值時的'self'是**模塊**,並且實例方法中的'self'是**實例**,因此兩個不同的'@ ftp'變量被引用。一種解決方案是爲'ftp'提供一個「getter」實例方法,如果它尚未定義,則分配給'@ ftp'。 –
我一直認爲依賴注入只是爲了測試代碼的氣味。 –