2012-09-18 5 views
1

나는 그 일을하기 전에 사용자가 로그인해야하는 SearchesController를 가지고있다.컨트롤러 테스트를 위해 로그인을 에뮬레이션하려면 어떻게해야합니까?

컨트롤러 테스트를 위해 로그인을 에뮬레이트하기 위해 rspec 도우미 기능 login을 작성하고 싶습니다. (NB : 통합/요청 사양을 별도로 처리합니다.) 내 시도가 제대로 작동하지 않았습니다. ApplicationController의 logged_in? 메서드는 false를 반환합니다.

질문 : 어떻게 '로그인'도우미를 작성합니까?

# file: spec/controllers/searches_controller_spec.rb 
require 'spec_helper' 
require 'controllers_helper' 
describe SearchesController do 
    include ControllersHelper 

    describe "GET index" do 

    it 'without login renders login page' do 
     get :index 
     response.should redirect_to(login_path) 
    end 

    it 'with login finds searches belonging to user' do 
     me = FactoryGirl.create(:user) 
     my_searches = FactoryGirl.create_list(:search, 2, :user => me) 
     not_me = FactoryGirl.create(:user) 
     not_my_searches = FactoryGirl.create_list(:search, 2, :user => not_me) 

     login(me) # want to define this in spec/controllers_helper.rb 
     get :index 
     assigns(:searches).should =~ my_searches 
    end 
    end 
end 

여기 컨트롤러의 :

# file: app/controllers/searches_controller.rb 
class SearchesController < ApplicationController 

    def index 
    unless logged_in? 
     redirect_to login_path, :alert => "You must be logged in to access this page." 
    else 
     @searches = Search.where(:user_id => current_user.id) 
     respond_to do |format| 
     format.html 
     format.json { render json: @searches } 
     end 
    end 
    end 

end 

을 그리고 여기와 ApplicationController 코드의

다음은 RSpec에 컨트롤러 테스트입니다. current_user = x은 x를 로깅하는 효과가 있으며, 이는 매우 간단합니다 : @current_user와 session [: user_id]를 설정한다는 점에 유의하십시오.

# file: app/controllers/application_controller.rb 
class ApplicationController < ActionController::Base 
    protect_from_forgery 
    force_ssl 

    protected 

    def current_user 
    @current_user ||= User.find_by_id(session[:user_id]) 
    end 

    def current_user=(user) 
    @current_user = user 
    session[:user_id] = user && user.id 
    end 

    def logged_in? 
    [email protected]_user 
    end 

    def require_login 
    unless logged_in? 
     redirect_to login_path, :alert => "You must be logged in to access this page." 
    end 
    end 

    helper_method :current_user, :logged_in?, :require_login 
end 

답변

1

내가 전에이 말을 모르지만, 스택 오버플로가 자신의 질문에 대답 배지를 주면, 나는 배지를 많이 가질 것! :)

좋아,이 질문에 대답하려면 documentation for ActionController::TestCase을 봐야합니다. 이렇게하면, 당신이에 대한 바인딩을 설정하는 것을 찾을 수 있습니다 다음 login 방법을 쓰는 OP에 주어진 특정 컨트롤러에 대한 그래서

@controller 
@request 
@response 

하는 것은 간단하다 :

# file: spec/controllers_helper.rb 
module ControllersHelper 
    def login(user) 
    @controller.send(:current_user=, user) 
    end 
end 

(I나요 누군가가 RTFM을 다시 듣는 것을 들었습니까? 나는 그렇게 생각했다 ...)

관련 문제