2016-10-01 101 views
0

我正在使用RSpec在Rails上測試我的類。RSpec - 調用應該模擬的私有方法的測試方法

我想知道什麼是測試調用私有方法的方法的好方法。

例如,我有這個類:

Class Config 
    def configuration(overrides) 
    @config.merge(overrides) 
    end 

    private 

    def read_config_from_yml 
    @config ||= YAML.load()... 
    end 
end 

要測試的配置方法,我們需要以某種方式嘲弄read_config_from_yml方法。我知道簡單地嘲諷私有方法read_config_from_yml或實例變量@config是不好的,因爲那樣會干擾對象的內部。

我能想到的在我的頭頂:

  1. 使read_config_from_yml公共

  2. 添加setter方法的配置(以避免嘲諷實例變量)

這些黑客?任何其他想法?

回答

0

一個想法是在測試中實際創建一個YAML文件的副本。您可以在生產代碼中使用您正在使用的文件片段,將其寫入預期的文件位置,並在測試完成後將其刪除。

before do 
    File.open(file_path_here, 'w+') do |f| 
    f << <<-eof 
     config: 
     setting1: 'string' 
     setting2: 0 
    eof 
    end 
end 

after do 
    File.delete(file_path_here) 
end 

it 'does the thing' do 
    ... 
end 

這樣可以避免任何瑕疵,並允許您保持私有方法。