Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a ruby class

Tags:

ruby

rspec

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?

like image 204
Sebastian Avatar asked Jul 13 '12 01:07

Sebastian


People also ask

What is reload in Ruby?

reload. Reloads the attributes of object(here @user) from the database. It always ensures object has latest data that is currently stored in database.

What is autoload in Ruby?

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.

How do you refresh a console?

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 does .class do in Ruby?

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.


2 Answers

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.

like image 102
Andrew Marshall Avatar answered Oct 16 '22 02:10

Andrew Marshall


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.

like image 42
David Grayson Avatar answered Oct 16 '22 00:10

David Grayson