Ruby on Rails 2.3.8:测试:如何在整个测试过程中设置一个实例变量?

时间:2011-06-21 15:34:20

标签: ruby-on-rails ruby unit-testing testing

让我们说我的一些数据在我的所有测试中都是相同的,永远和永恒。我在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

我知道我的实例变量不是null,因为在设置之后,我可以对它执行puts @ 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

禁用这些没有做任何事情。 =(

2 个答案:

答案 0 :(得分:0)

你试过吗

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

通常,如果在设置块中设置实例变量,它们应该可用于所有测试。 (您可能会遇到范围问题。)

答案 1 :(得分:0)

我的解决方案是创建一个共享类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