コントローラーのテスト内で、ログインしたときにコントローラーがリクエストを正常にレンダリングするか、ログインしていない場合は 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