나는 그 일을하기 전에 사용자가 로그인해야하는 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