I found that this question has a slightly different problem - clearing a cached class variable between rspec examples.
In the module, I have an expensive class config, which I cache as follows:
module Thingamizer def config @config ||= compute_config_the_hard_way() end end class Thing extend Thingamizer end
In my Thing tests for compute_config_the_hard_way only for the first time. Subsequent calls used the cached version, even if I make fun of compute_config_the_hard_way to return different things in other tests.
I solved this problem by clearing @config before each example:
before { Thing.instance_variable_set(:@config, nil) }
Now I was obsessed with @config being a class variable, not an instance variable. I tried many options for class_variable_set without luck.
The fold here is that the Thing (class) is actually an instance of the class. Thus, what seems to be a class variable in a class method is actually an instance variable in an instance of the class (i.e. Thing). Once I class_variable_set this idea, using instance_variable_set instead of class_variable_set made sense.
See Using instance variables in class methods - Ruby for a discussion of class variables as instance variables.
source share