In many of our classes we cache expensive operation for performance. e.g.
def self.foo
@foo ||= get_foo
end
This works great in the application, however the tests (RSpec) fail because of these memoized variables. The values from the first test are being returned in the subsequent tests, when we expect fresh values.
So the question is: how do I reload the class? Or remove all the memoized variables?
reload. Reloads the attributes of object(here @user) from the database. It always ensures object has latest data that is currently stored in database.
The Module#autoload method registers a file path to be loaded the first time that a specified module or class is accessed in the namespace of the calling module or class.
Simply type in the “reload!” command after making changes and the console will reload the session. The “reload!” command is limited in the sense that objects that were instantiated before the reload session will only have access to the initial code prior to any changes.
What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.
Add an after
(or before
) block to the example group to remove the instance variable (assuming the object in question is the subject):
after do
subject.instance_variable_set(:@foo, nil)
end
Or fix the problem. Having a memoized class instance variable is a bit of a smell since it will never change. Normal instance variables wouldn't have this issue since you'd create a new object for each test.
Build your classes and tests in such a way that the cached data remains correct or gets deleted when it is invalid. Consider adding a method to clear the cache and calling it in a rspec before
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With