2013-03-03 41 views
2

我有一個控制器,其索引操作密碼保護:的Rails需要登錄(使用cookie)測試行動

class Admin::UsersController < Admin::BaseController 
    before_action :signed_in_user 

    def index 
    @users = User.all 
    end 
end 

我有一個測試:

test "should get index" do 
    get :index 
    assert_response :success 
    assert_not_nil assigns(:users) 
end 

測試失敗,因爲用戶在運行時被重定向到登錄頁面:

def signed_in_user 
    unless signed_in?  
    redirect_to signin_url, notice: "Please sign in." 
    end 
end 

def signed_in? 
    !current_user.nil? 
end 

def current_user 
    @current_user ||= User.find_by_remember_token(cookies[:remember_token]) 
end 

def current_user=(user) 
    @current_user = user 
end 

def sign_in(user) 
    cookies.permanent[:remember_token] = user.remember_token 
    self.current_user = user 
end 

def current_user?(user) 
    user == current_user 
end 

我知道我可以使用水豚訪問信號否Page並登錄測試用戶,但在我的經驗,這通常會導致測試採取年齡運行的套房,所以我希望有可能是一個快速和骯髒的方式做到這一點使用會話:

test "should get index" do 
    get :index, { }, { remember_token: users(:one).remember_token } 
    assert_response :success 
    assert_not_nil assigns(:users) 
end 

# I also tried the following: 
test "should get index" do 
    get :index, { }, { current_user: users(:one) } 
    assert_response :success 
    assert_not_nil assigns(:users) 
end 

我希望上述內容能夠奇蹟般地記錄我的測試用戶,但是不會,並且我們仍然被重定向到登錄頁面,並且測試失敗。

做這種事情的正確方法是什麼?這讓我瘋狂。

回答

0

修好了,感謝this question。我需要的全部是:

setup do 
    @user = users(:one) 
    # since I am using cookies, I just need to set them here 
    @request.cookies['remember_token'] = @user.remember_token 
end 

# no need to pass anything to the get method 
test "should get index" do 
    get :index 
    assert_response :success 
    assert_not_nil assigns(:users) 
end