我有一个 SearchesController 需要用户登录才能执行它的操作。
我想编写一个 rspec 辅助函数login
来模拟控制器测试的登录。(注意:我将分别处理集成/请求规范。)我的尝试没有奏效:logged_in?
ApplicationController 中的方法返回 false。
问题:如何编写“登录”助手?
这是 RSpec 控制器测试:
# 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 代码。请注意,它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?
!!@current_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