简体   繁体   English

Ruby on Rails 2.3.8:Factory_girl:全局变量不能在整个工厂构建过程中保持价值吗?

[英]Ruby on Rails 2.3.8: Factory_girl: Global Variable doesn't maintain value throughout factory builds?

  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) 在我的单元测试中,我执行Factory.build(:object)

but in the factory itsself, it is saying NoMethodError: undefined method my_attribute for nil:NilClass 但在工厂本身,却说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 =\\ 但是@user是nil = \\

@user is not a global variable. @user不是全局变量。 It is an instance variable. 它是一个实例变量。 In this case, @user is an instance variable of the test suite. 在这种情况下, @user是测试套件的实例变量。 The do...end block passed to Factory.define is not run within the context of the test suite, therefor it will have a different self and different instance variables. 传递给Factory.definedo...end块不在测试套件的上下文中运行,因此它将具有不同的self和不同的实例变量。 Instead, you need to pass the attribute value to the factory: 相反,您需要将属性值传递给工厂:

setup do
  @user = Factory.build(:user)
  Factory.build(:object, :my_attribute => @user.my_attribute)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM