加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在ruby中的rspec测试之间清除类变量

发布时间:2020-12-16 20:26:18 所属栏目:百科 来源:网络整理
导读:我有以下类: 我想确保类url只为所有实例设置一次. class DataFactory @@url = nil def initialize()begin if @@url.nil? Rails.logger.debug "Setting url" @@url = MY_CONFIG["my value"] endrescue Exception raise DataFactoryError,"Error!"end endend
我有以下类:
我想确保类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类变量仍然从第一个测试中设置.
即使我在第一次测试结束时将实例设为零,垃圾回收未在第二次测试运行之前清除内存:

任何想法都会很棒!
我听说你可以使用Class.new,但我不知道该怎么做.

解决方法

describe DataFactory
  before(:each) { DataFactory.class_variable_set :@@url,nil }
  ...
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读