1

我有一个 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
4

1 回答 1

1

我之前可能说过,但如果 Stack Overflow 给徽章回答自己的问题,我就会有很多徽章!:)

好的,要回答这个问题,您需要查看ActionController::TestCase 的文档。当您这样做时,您会发现它为以下内容设置了绑定:

@controller
@request
@response

所以对于 OP 中给出的具体控制器,编写login方法很简单:

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

(我是不是又听到有人说 RTFM 了?我是这么想的……)

于 2012-09-19T00:30:08.193 回答