[rspec-users] Module instance variable remains set

Matt Wynne matt at mattwynne.net
Mon Feb 22 17:10:51 EST 2010


On 22 Feb 2010, at 19:45, Harm wrote:

> Hi,
>
> I have an issue with rSpec when spec'ing a module. The module in
> question looks like this:
>
> module Sheep
>  def self.sound
>    @sound ||= produce_sound()
>  end
> end
>
> This module is used all around the application (and corresponding
> specs) and somehow values of @sound leak between each spec. The only
> way I found to fix it is to manually set the instance variable (with
> instance_variable_set) to nil. Obviously this is Bad. Is there a way
> to do this globally or better yet to prevent this?

By using class methods like this, you're always going to have leaky  
state. Here's one way to work around this:

class Sheep
   class << self
     def reset!
       @instance = nil
     end

     private

     def method_missing(message, *args)
       instance.send(message, *args)
     end

     def instance
       @instance ||= new
     end
   end

   def sound
     @sound ||= produce_sound()
   end
end

Now you can call Sheep.reset! between examples, and you'll get a brand  
new Sheep instance each time. The old Sheep.sound API will still work  
fine.

The added bonus is you can now spec the Sheep class properly too,  
without having to worry about leaky state there either.

>
> With kind regards,
> Harm
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

cheers,
Matt

http://mattwynne.net
+447974 430184



More information about the rspec-users mailing list