簡體   English   中英

Ruby on Rails 2.3.8:測試:如何設置實例變量以在整個測試中使用?

[英]Ruby on Rails 2.3.8: Testing: How do I set up an instance variable to use throughout my tests?

可以說,我擁有一些數據,這些數據在我所有的測試中都存在,直到永遠。 我在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

我真的不認為我需要這兩種方法,因為當我在安裝程序中定義@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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM