Reputation: 65183
So.. here is the top of my unit test file.
class ObjectTest < ActiveSupport::TestCase
@user = -1
the test that fails (also the first one to use @user)
test "for detection of first content" do
puts "+++++++++++++++++++++++++++++ #{@user.name}"
And this is the error I get
NoMethodError: undefined method `name' for nil:NilClass
Now, I know that a number can't have any attributes like .name.. but I'm trying to solve a problem unrelated to trying to get the name of integers. The problem is that instance variable defined anywhere in my test file instantly turn to nil when na test begins -- as you can, the actual content of the test doesn't matter, the data inside @user is vanishing somehow. =\
Upvotes: 0
Views: 601
Reputation: 10564
Class instance variables are a little odd, and I've not used them that much, but if I grok them correctly, they exist on the class itself and can only be accessed with the @ symbol in class methods - so you will have to access @user
as ObjectTest.user
or self.class.user
when you are in instance methods, otherwise Ruby will look for the instance instance variable inside of instance methods. In other words, in a class function, you can refer to @user
, but in an instance function, Ruby is looking for the @user variable on the instance. here is a page that seems to demonstrate this behavior.
Since class variables (e.g. @@user
) use a completely different syntax, they should not show this scope-colliding behavior - you can use @@user
in both class and instance methods.
Upvotes: 2