Ruby remove all instance variables


634
634 points
remove all instance variables
remove all instance variables

Remove all instance variables

As most of us does , you might be using instance variables in your ruby tests. But if you need so , how you can remove all instance variables after each scenario.

What is an instance variable ?

Instance variables begin with an at sign (@) and can be referenced only within class methods. They differ from local variables in that they don’t exist within any particular scope. Instead, a similar variable table is stored for each instance of a class. Instance variables live within a class instance, so as long as that instance stays alive, so will the instance variables.

Remove all instance variables

Inside your hooks.rb you can add the following code :

After do |scenario|
  # Get an array of all the instance varaibles
  all_instance_variables = instance_variables

  # Set them all back to nil ready for the next test
  all_instance_variables.each do |variable|
    variable = nil
  end
end
Remove one instance variable
remove_instance_variable(:@variable_name)

So you might be asking why do I need to remove an instance variable, and why I don’t leave GC to take care of it. Well just imagine the following situation.

You have one step where you click on a link and that links opens a new browser tab

Advertisements
  @new_window = window_opened_by do
    within("#wpfooter") do
      click_link arg1
    end
  end

In the second step you try to do some assertions and you switch to the new opened tab.

  within_window @new_window do
    begin
      assert_true(current_url.include?(landing_url))
    ensure
      @new_window.close
      remove_instance_variable(:@new_window)
    end
  end

But in the same test session you have a similar scenario , where you open a new window , so in this case

@new_window

is still active , so your tests might fail because of that , so I choose to destroy it , either remove it within a try/catch statement either using the hooks.

Happy testing!


Like it? Share with your friends!

634
634 points
Test engineer

0 Comments

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.