Accessing a global variable in ruby ​​unit tests

I am having problems using the global variable defined in my test class that the library file refers to. I am using Ruby 1.9.3p392 and test block 2.5.4.

This is the code that runs the tests:

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 

And this is the part of the library that contains the login function:

 require 'rubygems' module Functions def login(url, user, passw) @browser.goto(url) ... end end 

This is the conclusion:

 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_user', '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 

Any ideas?

+4
source share
2 answers

Instance instances (i.e. @browser) defined in the startup method will not be available for testing. Based on this old forum thread, http://www.ruby-forum.com/topic/144884 , this is by design:

This is design behavior. The idea of ​​isolating a test implies that you don’t have to work too hard to get a clean list every time a test script starts. Otherwise, the test may rely on the @value value from the previous test and may rely on it the way you did not notice it.

Of course, any other constant variable can ruin the test isolation. We do not stop and restart Ruby between each test case. But at least when this happens, the @instance variables will not be to blame.

One of the workarounds that I used, I used to use the same browser in tests, to use a class variable (i.e. @@browser ). The launch will look as follows. Other methods must also be updated to use @@browser .

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

Your initialization code does not start before testing.

The TestUnit structure expects the installation code to have a method named setup , and the teardown code to expect in a method named teardown

You have two options to either rename the startup method to setup and the shutdown method to teardown , or if you need to set it on / off for other purposes, create delegate methods:

 def setup startup end def teardown shutdown end 
+3
source

All Articles