如何在rails 3中模拟/存储配置初始化程序哈希

MMi*_*has 3 rspec2 ruby-on-rails-3.1

环境:Rails 3.1.1 and Rspec 2.10.1 我通过外部YAML文件加载所有应用程序配置.我的初始化程序(config/initializers/load_config.rb)看起来像这样

AppConfig = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]
Run Code Online (Sandbox Code Playgroud)

我的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
Run Code Online (Sandbox Code Playgroud)

我可以访问这些值,例如 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
Run Code Online (Sandbox Code Playgroud)

在我各自的课堂上,我正在做这样的事情

class Policy        
 def eligible_month?
  eval(AppConfig['feesecure_eligible_months_for_monthly_payments']).include?(Date.today.month)
 end
....
end
Run Code Online (Sandbox Code Playgroud)

有人可以指出我正确的方向!

Fre*_*ung 6

执行时调用AppConfig['foo'][]方法是方法,它接受一个参数(要检索的键)

因此,你在测试中可以做的是

AppConfig.stub(:[]).and_return('1..11')
Run Code Online (Sandbox Code Playgroud)

您可以with根据参数的值设置不同的期望,即

AppConfig.stub(:[]).with('foo').and_return('1..11')
AppConfig.stub(:[]).with('bar').and_return(3)
Run Code Online (Sandbox Code Playgroud)

您不需要设置模拟AppConfig对象 - 您可以将您的存根直接放在'真实'对象上.