title: Rspec - How can I stub a constant that is defined in config/environment.rb?
body: <p>I have defined a constant in <code>config/environment.rb</code> called LOCAL_SETTINGS that I use for configuration and use throughout my app. It's a YAML file stored in <code>config/local_settings.yml</code> and will sometimes contain sensitive data like API keys etc.</p>
  
  <p>I'm currently trying to write a spec for a method that uses <code>LOCAL_SETTINGS["slack"]["slack_token"]</code>.</p>
  
  <p>The problem is that the constant is not being stubbed for my expectations.  ie <code>expect(subject.path).to eq(help_request)</code> fails because it returns a path including the non-stubbed <code>LOCAL_SETTINGS</code> hash.</p>
  
  <p>However if I put a debugger in beneath <code>stub_const</code> and then type <code>LOCAL_SETTINGS</code>, I can see that stub_const has worked.</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Is there something I can do in Rspec to get stubs working for constants defined in <code>config/environment.rb</code>?</li>
  <li>Should I simply define this constant elsewhere? If so, where? I will need access to it throughout my application in the app/ lib/ and spec/ folders.</li>
  </ol>
  
  <p>My <code>config/environment.rb</code> file:</p>
  
  <pre><code># Load the Rails application.
  require_relative 'application'
  
  LOCAL_SETTINGS = YAML.load_file("#{Rails.root}/config/local_settings.yml")
  
  # Initialize the Rails application.
  Rails.application.initialize!
  </code></pre>
  
  <p>My spec:</p>
  
  <pre><code>describe RequestBuilder, type: :model do
    let(:help_params) { {"user_name"=&gt;"some_user_name", "text"=&gt;"release-bot help"} }
    let(:help_builder) { RequestBuilder.new(help_params) }
    let(:help_request) { "/api/files.upload?file=lib%2Fresponses%2Fhelp&amp;filetype=ruby&amp;channels=stubbed_channel&amp;token=stubbed_token" }
    let(:slack_settings) { {"slack"=&gt;{"slack_token"=&gt;"stubbed_token", "slack_channel"=&gt;"stubbed_channel"}} }
  
    context 'Given an incoming request' do
      context 'With a correctly formatted request' do
        context 'And the "help" command' do
  
          subject { help_builder.build_request_hash }
  
          it 'builds a request containing the help data' do
            stub_const("LOCAL_SETTINGS", slack_settings)
  
            expect(subject).to have_key(:request)
            expect(subject[:request].path).to eq(help_request)
          end
        end
      end
    end
  end
  </code></pre>