Skip to content

Instantly share code, notes, and snippets.

@maxivak
Last active January 23, 2018 18:04
Show Gist options
  • Save maxivak/5f66b5ac73ca89370996 to your computer and use it in GitHub Desktop.
Save maxivak/5f66b5ac73ca89370996 to your computer and use it in GitHub Desktop.
RSpec 3

Mock application config variable

allow(Rails.application.config).to receive(:config_name).and_return('myvalue')

TODO: doesn't work in a certain situation:

http://stackoverflow.com/questions/26794443/rspec-stubbing-rails-application-config-value-doesnt-work-when-reopening-class

Mock environment variables

For testing code that depends on environment variables

Wrapping ENV

describe 'wrapping the environment' do
  it 'stubs the environment in the block' do
    actual_env = nil

    wrap_env('TEST_VAR' => 'changed') do
      actual_env = ENV['TEST_VAR']
    end

    expect(ENV['TEST_VAR']).to eq 'original'
    expect(actual_env).to eq 'changed'
  end
end

references:

Option 2

before :each do
  allow(ENV).to receive(:[]).with('myvariable').and_return('some_value')
  allow(ENV).to receive(:[]).and_call_original
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment