2012-06-19 31 views
3

環境:Rails 3.1.1 and Rspec 2.10.1 我正在通過外部YAML文件加載所有應用程序配置。我的初始化(config/initializers/load_config.rb)看起來像這樣如何在rails 3中模擬/存根配置初始化程序哈希

AppConfig = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV] 

我的YAML文件位於下的config/config.yml

development: 
client_system: SWN 
b2c_agent_number: '10500' 
advocacy_agent_number: 16202 
motorcycle_agent_number: '10400' 
tso_agent_number: '39160' 
feesecure_eligible_months_for_monthly_payments: 1..12 

test: 
client_system: SWN 
b2c_agent_number: '10500' 
advocacy_agent_number: 16202 
motorcycle_agent_number: '10400' 
tso_agent_number: '39160' 
feesecure_eligible_months_for_monthly_payments: 1..11 

我訪問這些值,例如AppConfig['feesecure_eligible_months_for_monthly_payments']

在我的測試中一個我需要AppConfig['feesecure_eligible_months_for_monthly_payments']才能返回不同的值,但不知道如何完成此操作。我嘗試以下方法,沒有運氣

describe 'monthly_option_available?' do 
before :each do 
    @policy = FeeSecure::Policy.new 
    @settlement_breakdown = SettlementBreakdown.new 
    @policy.stub(:settlement_breakdown).and_return(@settlement_breakdown) 
    @date = Date.today 
    Date.should_receive(:today).and_return(@date) 
    @config = mock(AppConfig) 
    AppConfig.stub(:feesecure_eligible_months_for_monthly_payments).and_return('1..7') 
end 
..... 
end 

在我的各階級,我做這樣的事情

class Policy   
def eligible_month? 
    eval(AppConfig['feesecure_eligible_months_for_monthly_payments']).include?(Date.today.month) 
end 
.... 
end 

可有人請點我在正確的方向!

回答

5

正被調用,當你做AppConfig['foo'][]方法,它接受一個參數(該鍵可檢索)

,你可以在您的測試做所以什麼方法是

AppConfig.stub(:[]).and_return('1..11') 

你可以使用with根據參數的值設置不同的期望,即

AppConfig.stub(:[]).with('foo').and_return('1..11') 
AppConfig.stub(:[]).with('bar').and_return(3) 

你不需要設置一個模擬AppConfig對象 - 你可以將你的存根直接放在「真實」的一個上。

+0

謝謝弗雷德裏克! – MMinhas

+0

你會如何存留AppConfig ['foo'] ['bar']? – MMinhas

+0

最簡單的事情可能是做與以前完全相同的存根,但不是返回值爲3,使它成爲'{'bar'=> 3}' –