2009-02-07 70 views
3

根據this Rails guide,如果您創建了一個燈具,它將在您的測試課程中可用。爲什麼在我的Rails Test :: Unit測試中我的fixture對象不可用?

我有這樣的支架,users.yml

<% 
    stan = User.new 
    stan.username = 'stan' 
    stan.set_hashed_password('mysterio') 
    stan.email = '[email protected]' 
%> 

stan: 
    username: <%= stan.username %> 
    hashed_password: <%= stan.hashed_password %> 
    password_salt: <%= stan.password_salt %> 
    email: <%= stan.email %> 

繼Rails的指導,我試圖訪問它是這樣的:

class SessionsControllerTest < ActionController::TestCase 

    @user = users(:stan) 

    # ... 

end 

我得到這個錯誤:

./test/functional/sessions_controller_test.rb:5: undefined method `users' for SessionsControllerTest:Class (NoMethodError) 
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' 
    from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' 
    from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:155:in `require' 

回答

4

感謝您的幫助球員。我意識到我有不同的聲明和調用結構不正確。這在我引用的指南中沒有清楚解釋,但顯然users(:stan)只能在should塊內工作,或者在test_方法內的純粹Test :: Unit中工作。

+1

是的,如果您在測試方法之外或應用程序塊之外使用它,那麼您將調用類方法,而不是實例方法。 – 2009-02-08 03:26:30

5

請確保你有

fixtures :all 

在你test_helper.rb中

7

嘗試把

fixtures :users 

類聲明後

+0

這對我很有效 - 即使我認爲我自己「當然所有的裝置都加載了」 - 他們沒有。謝謝。 – Docunext 2011-03-03 17:59:47

-1

這是一個超古老的問題,但是在閱讀rails tutorial book時,我遇到了類似的問題。

我在我的UsersLoginTest集成測試開始時有一個設置方法,出於某種原因,我在那裏引用的fixture,似乎沒有在測試中工作。爲了讓它工作,我必須在測試的頂部有一行@user = users(:michael)。

最後,我發現我已經複製了文件頂部的類聲明,由教程書中的LAZY複製和粘貼。因此,如果有其他人遇到與線程相關的類似問題而無法正常工作,請檢查您是否犯了與我一樣的愚蠢錯誤,並重覆文件頂部!

require 'test_helper' 

class UsersLoginTest < ActionDispatch::IntegrationTest 

    def setup 
    @user = users(:michael) 
    end 
相關問題