Module instance variable remains set

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?

With kind regards,
Harm

Addendum: I’m using rspec 1.3.0, rspec-rails 1.3.2 and ruby 1.9.1p129

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

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
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

cheers,
Matt

+447974 430184