How to reset constants in tests?

B

Ben Johnson

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!
 
D

David A. Black

Hi --

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

--
Rails training from David A. Black and Ruby Power and Light:
INTRO TO RAILS (Jan 12-15) | ADVANCING WITH RAILS (Jan 19-22) *
Both in Fort Lauderdale, FL * Co-taught with Patrick Ewing
See http://www.rubypal.com for details
Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top