# How to reset constants in tests?

**URL:** <https://www.ruby-forum.com/t/how-to-reset-constants-in-tests/154497>\
**Category:** Ruby\
**Created:** [November 30, 2008, 8:12pm UTC](https://www.ruby-forum.com/t/how-to-reset-constants-in-tests/154497 "2008-11-30T20:12:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [November 30, 2008, 8:12pm UTC](https://www.ruby-forum.com/t/how-to-reset-constants-in-tests/154497/1 "2008-11-30T20:12:02Z")

</div>

I am writing tests for configuration options that make class level  
changes. Because they are class level, the changes get carried over to  
the next test. What would be the best way to accomplish “transactions”  
for ruby constants. Basically a way to rollback any class level changes  
that were made during the test.

Thanks!

---

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [November 30, 2008, 8:23pm UTC](https://www.ruby-forum.com/t/how-to-reset-constants-in-tests/154497/2 "2008-11-30T20:23:29Z")

</div>

Hi –

On Mon, 1 Dec 2008, Ben J. wrote:

> I am writing tests for configuration options that make class level  
> changes. Because they are class level, the changes get carried over to  
> the next test. What would be the best way to accomplish “transactions”  
> for ruby constants. Basically a way to rollback any class level changes  
> that were made during the test.

The first thing that comes to mind is something like this (untested,  
and you’d have to adapt it a lot anyway):

def change\_option(const\_name, value, klass)  
old\_value = klass.const\_get(const\_name)  
klass.const\_set(const\_name, value)  
yield  
klass.const\_set(const\_name, old\_value)  
end

def test\_something  
change\_option(“OPTION”, value, klass) do  
…  
end  
end

David
