Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear class variables between rspec tests in ruby

Tags:

I have the following class: I want to ensure the class url is only set once for all instances.

class DataFactory   @@url = nil    def initialize() begin     if @@url.nil?        Rails.logger.debug "Setting url"        @@url = MY_CONFIG["my value"]     end rescue Exception   raise DataFactoryError, "Error!" end   end end 

I have two tests:

it "should log a message" do   APP_CONFIG = {"my value" => "test"}   Rails.stub(:logger).and_return(logger_mock)   logger_mock.should_receive(:debug).with "Setting url"    t = DataFactory.new   t = nil end  it "should throw an exception" do   APP_CONFIG = nil    expect {     DataFactory.new   }.to raise_error(DataFactoryError, /Error!/) end 

The problem is the second test never throws an exception as the @@url class variable is still set from the first test when the second test runs. Even though I have se the instance to nil at the end of the first test garbage collection has not cleared the memory before the second test runs:

Any ideas would be great! I did hear you could possibly use Class.new but I am not sure how to go about this.

like image 203
Kevin White Avatar asked Nov 25 '11 22:11

Kevin White


People also ask

How do I cancel RSpec?

One can stop the RSpec test in the middle by pressing ctrl-C twice.

How many types of variables are used in Ruby and what are they?

Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table. In addition, Ruby has two pseudo-variables which cannot be assigned values.

What is class variable in Ruby?

Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.


1 Answers

describe DataFactory   before(:each) { DataFactory.class_variable_set :@@url, nil }   ... end 
like image 186
Mori Avatar answered Sep 27 '22 21:09

Mori