Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload modules between RSpec tests with Ruby?

Tags:

module

ruby

rspec

I have a module that can be configured like so:

module MyModule
   mattr_accessor :setting
   @@setting = :some_default_value
end

MyModule.setting = :custom_value

I'm testing different configuration options with RSpec, and found that the settings persist between different tests because they are class variables.

What's the best way to reload and re-initialize the module in between RSpec tests?

like image 943
Niko Efimov Avatar asked Jul 13 '13 01:07

Niko Efimov


1 Answers

I came to this solution:

describe MyModule do

  before :each do
    # Removes the MyModule from object-space (the condition might not be needed):
    Object.send(:remove_const, :MyModule) if Module.const_defined?(:MyModule)

    # Reloads the module (require might also work):
    load 'path/to/my_module.rb'
  end

  it "should have X value" do
     MyModule.setting = :X

     expect(MyModule.setting).to eq :X
  end

end

Source: http://geminstallthat.wordpress.com/2008/08/11/reloading-classes-in-rspec/

like image 132
sequielo Avatar answered Sep 17 '22 23:09

sequielo