Skip to content

Instantly share code, notes, and snippets.

@stringsn88keys
Created July 7, 2017 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stringsn88keys/52251afa9955cd6c70cd439677ef4810 to your computer and use it in GitHub Desktop.
Save stringsn88keys/52251afa9955cd6c70cd439677ef4810 to your computer and use it in GitHub Desktop.
Stubbing Rails Settings
# a module included
module StubSettings
def stub_setting(setting_name, setting_value)
allow(Setting).to receive(:[]).with(setting_name).and_return(setting_value)
end
def stub_setting_assignment
allow(Setting).to receive(:[]=) { |setting, value| stub_setting(setting, setting) }
end
end
# in spec_helper.rb
config.before(:each) do
# detect if Settings being set without you knowing about it
allow(Setting).to receive(:[]=)
.and_raise("stub_setting(setting_name, setting_value) to set the value of a Setting instead")
# passthrough read-only settings calls (necessary if you don't want .with to block other settings
allow(Setting).to receive(:[]).and_call_original
end
# in rspec example
describe 'settings will be set in code invoked from here' do
# automatically stubs assigned value to new stub
before { stub_setting_assignment }
end
# stubbing a setting value
describe 'setting to be forced to a value' do
before { stub_setting('some_toggle_setting', true) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment