2012-06-20 88 views
7

Updating, showing, and deleting users, exercises哈特爾的Rails的教程第9章練習6

有沒有一種方法來創建一個RSpec測試用戶控制器動作,比如「創造」和「新的?」

我對兩種行爲「創造」和「新」本身之間的差異還不十分清楚;有人可以這麼好心地闡述一下嗎?

創建測試後,我該如何去實現redirect_to root_path?我認爲我應該在before_filter signed_in部分包含「新建」和「創建」操作,但這不會自動重定向到根目錄。

我試圖讓測試通過修改users_controller.rb文件傳遞如下:

def create 
    if signed_in? 
     redirect_to root_path 
    else 
     @user = User.new(params[:user]) 
     if @user.save 
     sign_in @user 
     flash[:success] = "Welcome to the Sample App!" 
     redirect_to @user 
     else 
     render 'new' 
     end 
    end 
    end 

回答

1
  1. 是;這部分開始於7.16和其他地方。
  2. 其中一個實際創建用戶(create)。一個用於的頁面創建一個新用戶(new)。
  3. 不知道我明白這個問題。
+0

請看我上面的編輯;希望它會提供一些清晰。我非常感謝你的幫助。由於某種原因,我之前無法評論這裏... – railser

+0

@ user1469059仍然不確定我的理解。 –

+0

如上所示修改users_controller.rb是否會將登錄用戶重定向到根路徑,但是否正常工作? – railser

10

我做了一個過濾器之前,似乎在測試我做這項工作做得很好, :上authentication_pages_spec.rb

describe "signin" do 
    describe "authorization" do 
    describe "for signed in users" do 
     let(:user) { FactoryGirl.create(:user) } 
     let(:new_user) { FactoryGirl.attributes_for(:user) } 
     before { sign_in user } 

     describe "using a 'new' action" do 
     before { get new_user_path } 
     specify { response.should redirect_to(root_path) } 
     end 

     describe "using a 'create' action" do 
     before { post users_path new_user } 
     specify { response.should redirect_to(root_path) } 
     end   
    end 
    end 
end 

像@WillJones說,有些人可能必須添加no_capybara: true到之前的區塊

和我的用戶控制器上:

before_filter :signed_in_user_filter, only: [:new, :create] 

def signed_in_user_filter 
    redirect_to root_path, notice: "Already logged in" if signed_in? 
end 

對於新的創造行爲之間的區別,它與REST建築風格做,但基本上,new是從用戶控制器,它響應一個GET請求,是一個最負責返回的動作查看它響應(在這種情況下,一個新的用戶表單)。另一方面,create是一個響應POST請求的動作,它不會呈現任何內容(它可以使用javascript進行響應,但這是一個高級主題),它是負責創建新用戶的動作,如動作的名稱暗示。

+0

這幫了我很多,謝謝! – wikichen

+3

爲了讓我的工作,我不得不通過'之前{sign_in用戶,no_capybara:true}'並通過'users_path(用戶)'。只爲他人的信息! – WillJones

+0

@WillJones:謝謝。我盯着它45分鐘,並在no_capybara的小費:真正救了我。 –

0

我之前也做了一個過濾器,但我的過濾器是不同的,我不明白它爲什麼起作用。

我的用戶控制器具有以下條目

class UsersController < ApplicationController 
. 
. 
    before_filter :logged_in_user, only: [:new, :create] 
. 
. 
def logged_in_user 
     redirect_to(root_path) if !current_user?(@user) 
    end 

它工作得很好,在rkrdo的例子和相應的測試通過。但這是否意味着current_user與用戶登錄時的用戶不同,反之呢?在我看來,他們在第一種情況下應該是平等的,不應該在第二種情況下。

相關問題