RubyonRails 2.3.8:测试:如何设置一个实例变量以在整个测试中使用



假设我有一些数据在我的所有测试中都是相同的,无论是永远的还是永恒的。我在setup中创建此数据。我将数据存储到@instance_var。但当我在任何测试中调用@instance_var.attribute时,我都会得到以下错误:

RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

我知道我的实例变量不为空,因为在设置它之后,我可以对它执行Put@instance_var.inspect…

有什么想法吗?

编辑:

 setup do
    user = Factory(:user)
    account = Factory(:account)    
    set_user(user)
    set_account(account)

    puts "||||||||||||||||||||||||||||||||||||||||||||||" #this proves that the instance vars are not null
    puts "| object_test.rb                            |"
    puts "|      #{@user.name}                   "
    puts "|      #{@account.name}                "
    puts "||||||||||||||||||||||||||||||||||||||||||||||"
  end

测试失败(出现上述错误)

test "for detection of first content with multiple contents" do
      object = Factory(:object, :user_id => @user.id, :account_id => @account.id)
   ... #the rest of this test isn't important, as it is the above line, on @user, where the nil.id error occers

在test_helper.rb 中

def set_user(user)
  @user = user
end
def set_account(account)
  @account = account
end

我真的不认为我需要这两种方法,因为当我在setup中定义@instance变量时,我得到了相同的结果

在test_helper.rb中,ActiveSupport::TestCase:之前设置了一些常量

  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
  fixtures :all

禁用这些功能没有任何作用=(

你试过吗

setup do
  @user = Factory(:user)
  @account = Factory(:account)
end

通常,如果您在设置块中设置实例变量,那么它们应该可用于所有测试。(您可能有作用域问题。)

我的解决方案是创建一个共享类shared_test.rb

require 'test_helper'
class SharedTest
  def self.initialize_testing_data
    self.reset_the_database
    self.set_up_user_and_account
    # make sure our user and account got created 
    puts "|||||||||||||||||||||||||||||||||||||||||||||"
    puts "| The user and account "
    puts "| we'll be testing with:"
    puts "|             #{@user.name}"
    puts "|             #{@user.account.name}"
    puts "|||||||||||||||||||||||||||||||||||||||||||||"
  end
  def self.reset_the_database
    #clear the database and reset it
    call_rake("db:test:prepare")
    call_rake("db:bootstrap RAILS_ENV=test")
  end
  def self.set_up_user_and_account
    #set up our user for doing all our tests (this person is very busy)  
    @user = Factory(:user)
    @account = Factory(:account)    
    @user.account = @account
    @user.save
  end
end

因此,在每个需要用户和帐户在所有测试之间保持不变的测试文件的顶部,您只需执行

require 'shared_test.rb'

方法被称为

SharedTest.initialize_testing_data 

最新更新