A clean solution to reset class variables between rspec checks

Is there a better way to clear class variables between Rspec tests than clear them from the after (: each) method? I would prefer to β€œclear them all”, instead of remembering to add them to config.after every time again ...

config.after(:each) do DatabaseCleaner.clean Currency.class_variable_set :@@default, nil end 
+6
source share
3 answers

I finally implemented this by pointing the method in lib / auto_clean_class_variables.rb to reset all class variables of this class

 module AutoCleanClassVariables def reset_class_variables self::CLASS_VARIABLES_TO_CLEAN.each do |var| class_variable_set var, nil end end end 

and calling this method from config.after (: each) located in spec_helper.rb

 config.append_after(:each) do DatabaseCleaner.clean # Find all ActiveRecord classes having :reset_class_variables defined classes = ActiveSupport::DescendantsTracker.descendants(ActiveRecord::Base) classes.each do |cl| if cl.methods.include?(:reset_class_variables) cl.reset_class_variables end end end 

Models that need to be β€œcleaned” can load this behavior:

 extend AutoCleanClassVariables CLASS_VARIABLES_TO_CLEAN = [:@@default] 

Thus, everything works fine, and there is no (unnecessary) reloading of the class, leading to problems if you try to compare the objects of these classes with each other (see my previous comment)

+6
source

After each run, you can reload the class:

 after(:each) do Object.send(:remove_const, 'Currency') load 'currency.rb' end 

See: Testing RSpec Class Variables

+3
source

include this in your spec_helper.rb

 Spec::Runner.configure do |config| config.before(:all) {} config.before(:each) { Class.class_variable_set :@@variable, value } config.after(:all) {} config.after(:each) {} end 

This will do what you choose before each other test. The decision made did not allow at least 2 cases when I needed a class variable reset.

+1
source

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


All Articles