在控制器测试中,我想测试登录时,控制器会呈现请求,否则如果未登录,它会重定向到 login_path。
第一个测试按预期顺利通过,没有用户登录,因此请求被重定向到 login_path。但是,我尝试了无数的 stub/stub_chain,但仍然无法通过测试来伪造正在登录的用户并呈现页面正常。
我会很感激一些让这个按预期工作的方向。
以下类和测试是保持问题简洁的基本要素。
应用控制器
class ApplicationController < ActionController::Base
include SessionsHelper
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
会话助手
module SessionsHelper
def logged_in?
redirect_to login_path, :notice => "Please log in before continuing..." unless current_user
end
end
应用控制器
class AppsController < ApplicationController
before_filter :logged_in?
def index
@title = "apps"
end
end
apps_controller_spec.rb
require 'spec_helper'
describe AppsController do
before do
@user = FactoryGirl.create(:user)
end
describe "Visit apps_path" do
it "should redirect to login path if not logged in" do
visit apps_path
current_path.should eq(login_path)
end
it "should get okay if logged in" do
#stubs here, I've tried many variations but can't get any to work
#stubbing the controller/ApplicationController/helper
ApplicationController.stub(:current_user).and_return(@user)
visit apps_path
current_path.should eq(apps_path)
end
end
end