【问题标题】:How to mock/stub the config initializer hash in rails 3如何在 Rails 3 中模拟/存根配置初始值设定项哈希
【发布时间】:2012-06-19 06:11:23
【问题描述】:

环境: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]

我的 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

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

【问题讨论】:

    标签: ruby-on-rails-3.1 rspec2


    【解决方案1】:

    执行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 对象 - 您可以将存根直接粘贴在“真实”对象上。

    【讨论】:

    • 如何存根 AppConfig['foo']['bar'] 之类的东西??
    • 最简单的事情可能是做与以前完全相同的存根,但返回值不是 3,而是{'bar' => 3}
    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2011-11-23
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多