ruby-on-railsrubyrspecconfigruby-on-rails-4.2

Mock Rails 4 application config custom value


In Rails::Application, I add a custom configuration using...

config.x.cache_config = config_for(:cache)

In my tests, I want to see how code using this behaves depending on how the configuration is defined in cache.yml. To set the various conditions in my rspec tests, I want to do something like...

allow(Rails.application.config.x).to recieve(:cache_config).and_return({})

But this doesn't work. It gets an error stating

#<Rails::Application::Configuration::Custom ... > does not implement: cache_config

Solution

  • After much digging and testing in pry, I figured this out.

    Short answer:

    allow(Rails.application.config.x).to receive(:method_missing).with(:cache_config).and_return({})
    

    Everything in this statement has to be exact except...

    Longer answer:

    If you want to dig into why this is, since it is not at all obvious, check out the code at...