Search code examples
ruby-on-railsrspecrspec-rails

How to stub Rails secret in RSpec?


Now that Rails comes with credential/secret file I can't seem to stub/override a secret with RSpec.

# credentials.yml.enc
my_token: 111

With environment variable we used to do

allow(ENV).to receive(:[]).with('my_token').and_return('')

So I was expecting to be able to apply the same logic like

allow(Rails.application.credentials).to receive(:my_token).and_return('')

But it does not override Rails secret. Any idea? Thanks


Solution

  • Should be straight forward as described here https://github.com/rspec/rspec-rails/issues/2099#issuecomment-472965256

    describe 'Credentials' do
      it 'stubs credentials' do
        allow(Rails.application.credentials).to receive(:my_token).and_return('123')
        expect(Rails.application.credentials.my_token).to eq('123')
      end
    end