如何清除ruby中rspec测试之间的类变量
问题描述:
我有以下类:
我想确保类url只为所有实例设置一次。
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
我有两个测试: / p>
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
问题是第二个测试永远不会抛出异常,因为@@ url类变量仍然设置从第一个测试第二个测试运行时。
虽然我在第一个测试的结尾处有nil实例垃圾回收在第二个测试运行之前没有清除内存:
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:
任何想法会很好!
我听说你可能使用Class.new,但我不知道该怎么做。
Any ideas would be great! I did hear you could possibly use Class.new but I am not sure how to go about this.
答
describe DataFactory
before(:each) { DataFactory.class_variable_set :@@url, nil }
...
end