1
我有一個SearchesController,需要用戶登錄才能完成任務。如何模擬登錄進行控制器測試?
我想寫一個rspec幫助函數login
來模擬登錄進行控制器測試。 (注意:我將分別處理集成/請求規範。)我的嘗試沒有成功:ApplicationController中的logged_in?
方法返回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 in的效果,它很簡單:它設置@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