Ruby on Rails 2.3.8:Factory_girl:全局变量在工厂构建过程中不保持值?
setup do
@user = Factory.build(:user)
end
因此,在单元测试的顶部,我有上述内容。
在我的单元测试中,我做了 Factory.build(:object)
但在工厂本身中,它说 NoMethodError: undefined method my_attribute for nil:NilClass
我的工厂:
Factory.define :object |o| do
o.my_attribute @user.my_attribute
end
但@user 为零=\
setup do
@user = Factory.build(:user)
end
so, at the top of my unit test, I have the above.
And in my unit tests, I do Factory.build(:object)
but in the factory itsself, it is saying NoMethodError: undefined method my_attribute for nil:NilClass
my factory:
Factory.define :object |o| do
o.my_attribute @user.my_attribute
end
but @user is nil =\
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@user
不是全局变量。它是一个实例变量。在本例中,@user
是测试套件的实例变量。传递给Factory.define
的do...end
块不在测试套件的上下文中运行,因此它将具有不同的self
和不同的实例变量。相反,您需要将属性值传递给工厂:@user
is not a global variable. It is an instance variable. In this case,@user
is an instance variable of the test suite. Thedo...end
block passed toFactory.define
is not run within the context of the test suite, therefor it will have a differentself
and different instance variables. Instead, you need to pass the attribute value to the factory: