如何清除 ruby 中 rspec 测试之间的类变量
我有以下课程: 我想确保类 url 只为所有实例设置一次。
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
我有两个测试:
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,但在第二个测试运行之前垃圾收集尚未清除内存:
任何想法都很棒! 我确实听说你可以使用 Class.new 但我不知道如何去做。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是已接受答案的替代方案,虽然不能解决您的特定示例,但我希望它可以帮助一些有同样问题的人。如果相关类没有指定默认值,并且在设置之前保持未定义,则这似乎有效:
对我来说适用于具有类似以下内容的类:
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:
Works for me with a class with something more like: