[英]Ruby on Rails 2.3.8: Testing: Instance Variable Nil, when declared at top of class?
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) 失败的测试(也是第一个使用@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. 现在,我知道一个数字不能有任何属性,如.name ..但我试图解决一个与试图得到整数名称无关的问题。 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. 问题是我的测试文件中任何地方定义的实例变量在测试开始时立即变为零 - 尽可能地,测试的实际内容无关紧要,@ user内部的数据正在以某种方式消失。 =\\ = \\
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. 类实例变量有点奇怪,我没有那么多使用它们,但是如果我正确地理解它们,它们就存在于类本身上,并且只能在类方法中使用@符号进行访问 - 所以你必须访问它们当您在实例方法中时, @user
作为ObjectTest.user
或self.class.user
,否则Ruby将在实例方法中查找实例实例变量 。 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 . 换句话说,在类函数中,您可以引用@user
,但在实例函数中,Ruby正在查找实例上的@user变量。 here is a page that seems to demonstrate this behavior. 这是一个似乎演示此行为的页面。
Since class variables (eg @@user
) use a completely different syntax, they should not show this scope-colliding behavior - you can use @@user
in both class and instance methods. 由于类变量(例如@@user
)使用完全不同的语法,因此它们不应显示此范围冲突行为 - 您可以在类和实例方法中使用@@user
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.