Reputation: 2213
I have a module that can be configured like so:
module MyModule
mattr_accessor :setting
@@setting = :some_default_value
end
MyModule.setting = :custom_value
I'm testing different configuration options with RSpec, and found that the settings persist between different tests because they are class variables.
What's the best way to reload and re-initialize the module in between RSpec tests?
Upvotes: 11
Views: 6395
Reputation: 1631
I came to this solution:
describe MyModule do
before :each do
# Removes the MyModule from object-space (the condition might not be needed):
Object.send(:remove_const, :MyModule) if Module.const_defined?(:MyModule)
# Reloads the module (require might also work):
load 'path/to/my_module.rb'
end
it "should have X value" do
MyModule.setting = :X
expect(MyModule.setting).to eq :X
end
end
Source: http://geminstallthat.wordpress.com/2008/08/11/reloading-classes-in-rspec/
Upvotes: 5
Reputation: 15788
1: Did you try requiring the file in a before :each
block?
require 'my_module'
2: I don't know if reloading a file is the right thing to do here. From what it seems all you want is some class's values to become default again, for that I'd just create a method that changes the module's values to whatever I wish.
describe MyModule do
def module_to_default
MyModule.setting = :some_default_value
end
before :each do
module_to_default
end
end
If you see a good use for defaulting this module values in your code it may even be a good idea to move the method into the module itself.
Upvotes: 0