Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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