环境: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
有人可以指出我正确的方向!!
答案 0 :(得分: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对象 - 您可以将存根直接贴在“真实”对象上。