如何清除ruby中rspec测试之间的类变量 [英] How can I clear class variables between rspec tests in ruby
本文介绍了如何清除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
这篇关于如何清除ruby中rspec测试之间的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文