Forum: Ruby How to reset constants in tests?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ben J. (Guest)
on 2008-11-30 21:12
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!
David A. Black (Guest)
on 2008-11-30 21:23
(Received via mailing list)
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
This topic is locked and can not be replied to.