如何模拟登录控制器测试?

时间:2012-09-18 23:32:51

标签: ruby-on-rails-3 rspec controller

我有一个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的效果,而且非常简单:它设置@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

0 个答案:

没有答案