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

在ruby单元测试中访问全局变量

发布时间:2020-12-17 02:38:23 所属栏目:百科 来源:网络整理
导读:我在使用我的测试类中定义的全局变量时遇到问题,然后在库文件中引用该变量.我使用的是 Ruby 1.9.3p392和测试单元2.5.4. 这是运行测试的代码: require 'rubygems'gem 'test-unit'require 'test/unit'require 'ci/reporter/rake/test_unit_loader'load '../li
我在使用我的测试类中定义的全局变量时遇到问题,然后在库文件中引用该变量.我使用的是 Ruby 1.9.3p392和测试单元2.5.4.

这是运行测试的代码:

require 'rubygems'
gem 'test-unit'
require 'test/unit'
require 'ci/reporter/rake/test_unit_loader'
load '../lib/functions.rb'
require 'watir'

class Test_002 < Test::Unit::TestCase

  include Functions

  class << self
   def startup
      @browser = Watir::Browser.new :ie
      @browser.speed = :fast
    end

    def shutdown
      @browser.close
    end
  end

  def test_001_login
    login('some_url','some_user','some_passw')
  end
end

这是包含登录功能的库的一部分:

require 'rubygems'

 module Functions 

  def login(url,user,passw)
    @browser.goto(url)
    ...
  end
end

这是输出:

Started
E
===============================================================================
Error: test_001_login(Test_002)
  NoMethodError: undefined method `goto' for nil:NilClass
(...)
     23:   end
     24:   
     25:   def test_001_login
  => 26:     login('some_url','some_passw')
     27:   end
     28:    
     29: end
===============================================================================

Finished in 3.0043 seconds.

1 tests,0 assertions,0 failures,1 errors,0 pendings,0 omissions,0 notifications
0% passed

0.33 tests/s,0.00 assertions/s

有任何想法吗?

解决方法

启动方法中定义的实例变量(即@browser)将无法用于测试.基于这个旧论坛帖子,http://www.ruby-forum.com/topic/144884,它是按设计:

That behavior is by design. The “test isolation” ideal implies you shouldn’t need to work too hard to get a clean slate each time a test case starts. Otherwise a test could rely on a @value from the previous test,and could rely on it in a way you don’t notice.

Of course any other persistent variable could ruin test isolation. We don’t stopand restart Ruby between each test case. But at least when it happens the @instance variables won’t be to blame.

我曾经使用的一种解决方法是我曾经在测试中使用相同的浏览器是使用类变量(即@@ browser).启动将如下所示.同样必须更新其他方法以使用@@ browser.

def startup
  @@browser = Watir::Browser.new :ie
  @@browser.speed = :fast
end

(编辑:李大同)

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

    推荐文章
      热点阅读