2013-02-10 59 views
2

這個想法是讓管理員用戶不能自我毀滅。 我寫了下面的測試:railstutorial.org,第9章練習,9

describe "as admin user" do 
    let(:admin) { FactoryGirl.create(:admin) } 
    before { valid_signin admin } 

    describe "should not be able to delete himself by submitting a DELETE request to the Users#destroy action" do 
    specify do 
     expect { delete user_path(admin) }.not_to change(User, :count).by(-1) 
    end 
    end 
end 

,因此修改了銷燬行動:

def destroy 
    @user = User.find(params[:id]) 
    unless current_user?(@user) 
    User.find(params[:id]).destroy 
    flash[:success] = "User destroyed." 
    redirect_to users_url 
    end 
end 

(你只能如果你是一個管理員用戶訪問銷燬行動)。

該測試現在應該通過,但它沒有。我收到以下錯誤消息:

Failure/Error: expect { delete user_path(admin) }.not_to change(User, :count).by(-1) 
    ActionView::MissingTemplate: 
     Missing template users/destroy, application/destroy with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. 

我不明白缺少的模板錯誤消息,我不明白爲什麼測試不通過。

回答

5

試着改變你的destroy行動,這樣的事情,看看你的測試通過:

def destroy 
    user = User.find(params[:id]) 
    unless current_user?(user) 
    user.destroy 
    flash[:success] = "User destroyed." 
    else 
    flash[:error] = "You can't destroy yourself." 
    end 
    redirect_to users_url 
end 

我認爲這個問題是,你只能重定向到users_url如果你成功摧毀一個用戶。如果你沒有(即管理員試圖摧毀自己),那麼沒有重定向,Rails將開始尋找名爲destroy.html.erb的視圖,在任何地方找不到,並引發異常。這也是爲什麼方法中的用戶變量從@user更改爲user:本地變量將代替實例變量,因爲它不需要在視圖中使用。

如果這不是問題,請編輯您的問題以包含Github回購與您當前的代碼的鏈接。

+0

現貨,謝謝。現在完美運作。 – Bazley 2013-02-10 09:29:37