How can I clear class variables between rspec test

2019-06-14 22:07发布

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.

2条回答
forever°为你锁心
2楼-- · 2019-06-14 22:24
describe DataFactory
  before(:each) { DataFactory.class_variable_set :@@url, nil }
  ...
end
查看更多
神经病院院长
3楼-- · 2019-06-14 22:48

Here is an alternative to the accepted answer, which while wouldn't solve your particular example, I'm hoping it might help a few people with a question in the same vein. If the class in question doesn't specify a default value, and remains undefined until set, this seems to work:

describe DataFactory
  before(:each) do
    DataFactory.remove_class_variable :@@url if DataFactory.class_variable_defined? :@@url
  end
  ...
end

Works for me with a class with something more like:

def initialize
  @@url ||= MY_CONFIG["my value"]
  ...
end
查看更多
登录 后发表回答