如何在 rails 3 中模拟/存根配置初始值设定项哈希 [英] How to mock/stub the config initializer hash in rails 3

查看:59
本文介绍了如何在 rails 3 中模拟/存根配置初始值设定项哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Environment : Rails 3.1.1 and Rspec 2.10.1 I am loading all my application configuration through an external YAML file. My initializer (config/initializers/load_config.rb) looks like this

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

我的 YAML 文件位于 config/config.yml

And my YAML file sits under 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'] 返回不同的值,但我不确定如何实现.我尝试了以下方法但没有运气

In one of my tests I need AppConfig['feesecure_eligible_months_for_monthly_payments'] to return a different value but am not sure how to accomplish this. I tried the following approach with no luck

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

在我各自的班级中,我正在做这样的事情

In my respective class I am doing something like this

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

有人能指出我正确的方向吗!!

Can someone please point me in the right direction!!

推荐答案

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

The method that is being called when you do AppConfig['foo'] is the [] method, which takes one argument (the key to retrieve)

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

Therefore what you could do in your test is

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

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

You can use with to setup different expectations based on the value of the argument, ie

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

您无需设置模拟 AppConfig 对象 - 您可以将存根直接贴在真实"对象上.

You don't need to setup a mock AppConfig object - you can stick your stub straight on the 'real' one.

这篇关于如何在 rails 3 中模拟/存根配置初始值设定项哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆