RSpec recipe: remove constants created during a test execution

Dmitry Shvetsov
1 min readNov 24, 2017

--

Sometimes you want to create a fake object for a test, it can be especially the case when you are creating a ruby gem. You need to declare some classes, structs maybe even modules and use them inside your tests. But it is important to maintain a clean state between tests. Declared classes, modules, structs are global constants, they pollute the global namespace. This is a problem.

In RSpec you can solve this using an around hook and remove all constants declared during a test. Here is the solution:

You can play around with the code by cloning the repo. Any feedback would be greatly appreciated

November 26 Update:

Robert @lobatifricha point a better way if you only need to pass created class as an argument to a method that you are testing.

--

--