How to mock/stub the config initializer hash in rails 3

rspec2, ruby-on-rails-3.1

Solution

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')

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)

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

Problem

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] ``` 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 ``` And I access these values as, For example `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!!

Original source