How to reload modules between RSpec tests with Ruby?

I have a module that can be configured like this:

module MyModule mattr_accessor :setting @@setting = :some_default_value end MyModule.setting = :custom_value 

I am testing various configuration parameters with RSpec and found that settings are saved between different tests because they are class variables.

What is the best way to reload and reinitialize a module between RSpec tests?

+6
source share
2 answers

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/

+2
source

1: Have you tried to require a file in a before :each block?

 require 'my_module' 

2: I do not know if reloading the file is correct. From what it seems to you, all you need is some class values ​​that will become standard again, because I just create a method that modifies the module values ​​anyway.

 describe MyModule do def module_to_default MyModule.setting = :some_default_value end before :each do module_to_default end end 

If you well understand the use of the values ​​of this module in your code, it might be a good idea to move the method to the module itself.

0
source

Source: https://habr.com/ru/post/949349/


All Articles