2015-04-22 101 views
0

我正在使用Michael Hartl的rails教程(chapter 9)。rails NoMethodError:undefined方法「」爲零:NilClass

我得到這個錯誤:在chapter 8加入

Error: 
UsersLoginTest#test_login_with_remembering: 
NoMethodError: undefined method `FILL_IN' for nil:NilClass 
    test/integration/users_login_test.rb:42:in `block in <class:UsersLoginTest>' 

填寫及有沒有,直到第9章 我嘗試了很多什麼問題,但我不能修復它。這是我的UsersLoginTest類。 42

class UsersLoginTest < ActionDispatch::IntegrationTest 

    def setup 
    @user = users(:michael) 
    end 

    test "login with invalid information" do 
    get login_path 
    assert_template 'sessions/new' 
    post login_path, session: { email: "", password: "" } 
    assert_template 'sessions/new' 
    assert_not flash.empty? 
    get root_path 
    assert flash.empty? 
    end 

    test "login with valid information followed by logout" do 
     get login_path 
    post login_path, session: { email: @user.email, password: 'password' } 
    assert is_logged_in? 
    assert_redirected_to @user 
    follow_redirect! 
    assert_template 'users/show' 
    assert_select "a[href=?]", login_path, count: 0 
    assert_select "a[href=?]", logout_path 
    assert_select "a[href=?]", user_path(@user) 
    delete logout_path 
    assert_not is_logged_in? 
    assert_redirected_to root_url 
    # Simulate a user clicking logout in a second window. 
    delete logout_path 
    follow_redirect! 
    assert_select "a[href=?]", login_path 
    assert_select "a[href=?]", logout_path,  count: 0 
    assert_select "a[href=?]", user_path(@user), count: 0 
    end 

    test "login with remembering" do 
    log_in_as(@user, remember_me: '1') 
    assert_equal assigns(:user).FILL_IN, FILL_IN 
    end 

    test "login without remembering" do 
    log_in_as(@user, remember_me: '0') 
    assert_nil cookies['remember_token'] 
    end 
end 

線是:

assert_equal assigns(:user).FILL_IN,FILL_IN 

回答

1

FILL_IN在這種情況下是一個佔位符。邁克爾希望你用正確的文字替換它。

2

錯誤表明assigns(:user)返回零。

assigns測試控制器中設置的實例變量。期望的是,您的控制器中設置的值爲@user,並且調用方法FILL_IN時,它將等於FILL_IN。一旦解決了@usernil的問題,您需要實際填寫這些佔位符。

7

如果您在清單8.62中做了「記憶練習登錄」,則需要在清單9.29中使用@user實例變量。我花了一段時間來實現這一點,所以它可能會幫助其他初學者看看沙德韋爾的建議看起來像代碼:

sessions_controller.rb

class SessionsController < ApplicationController 
    # ... 

    def create 
    @user = User.find_by(email: params[:session][:email].downcase) 
    if @user && @user.authenticate(params[:session][:password]) 
     log_in @user 
     params[:session][:remember_me] == '1' ? remember(@user) : forget(@user) 
     redirect_back_or @user 
    else 
     flash.now[:danger] = 'Invalid email/password combination' # Flash.now designed for rendered pages, disappears at the next request. 
     render 'new' 
    end 
    end 

    # ... 
end 

users_login_test.rb

# ... 

test "login with remembering" do 
    log_in_as(@user, remember_me: '1') 
    assert_equal assigns(:user).remember_token, cookies['remember_token'] 
    end 

# ... 

爲了公平起見,Michael Hartl建議我們用git解決單獨主題分支中的練習。

相關問題