Created
July 7, 2017 14:34
-
-
Save stringsn88keys/52251afa9955cd6c70cd439677ef4810 to your computer and use it in GitHub Desktop.
Stubbing Rails Settings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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