我是存根/嘲笑的新手。
如何从外部库中存根方法,以便我只能测试模块的方法而不实际调用库?
另外,我想知道,我编写这个模块的方法是可行的还是违反了一些重要的编程原则?
# file_module.rb
module FileModule
require 'net/ftp'
@ftp = nil
def self.login
if !@ftp || @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