[英]Rails4 + Authlogic + rspec
使用Rails 4,我在讓Authlogic看到我偽造的UserSession時遇到問題。
我已經設置了#whoami頁面來呈現當前用戶的電子郵件地址,這是一個簡單的測試。
class PagesController < ApplicationController
# before_filter :require_user
def whoami
render :text => current_user.try(:email) || 'anonymous'
end
end
在spec / spec_helper.rb中:
require "authlogic/test_case"
include Authlogic::TestCase
和我的rspec測試:
require 'spec_helper'
describe '/whoami' do
setup :activate_authlogic
it "should tell me who I am" do
user = FactoryGirl.create(:user)
user.should be_valid
session = UserSession.create(user)
session.should be_valid
get '/whoami'
response.body.should == user.email
end
end
我更新了我的應用程序控制器以顯示當前會話:
def require_user
unless current_user
raise "Current User Session is: #{ current_user_session.inspect}"
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to new_user_session_url
return false
end
end
使用before_filter:require_user注釋,我正確地得到“匿名”。 當我取消注釋它時,我看到我的用戶會話為零。 我嘗試查看authlogic代碼但迷失在Authlogic :: Session:Persistence :: InstanceMethods #persisting?
我正在嘗試調試。 這是我到目前為止的地方。
在這里,我們嘗試將Authlogic :: Session :: Base.controller設置為測試的模擬控制器: https : //github.com/binarylogic/authlogic/blob/master/lib/authlogic/test_case.rb#L109
在我的規范中,我看到@controller是一個Authlogic :: TestCase :: MockController
在我的規范中,我看到Authlogic :: Session :: Base.controller被設置為該模擬控制器。
但是,我檢查一下:
class ApplicationController < ActionController::Base
...
def current_user_session
raise Authlogic::Session::Base.controller.inspect
...
end
end
我看到Authlogic :: ControllerAdapters :: RailsAdapter ...所以不知何故控制器正在設置但不持久。 我想知道這是否與從Rails3到Rails4的切換有關?
任何洞察這一點將不勝感激。
對於那些感興趣的寶石版本:gem rspec-core(2.14.5)gem authlogic(3.3.0)gem rails(4.0.0)
根據https://stackoverflow.com/a/5803121 ,請求規范只是ActionDispatch::IntegrationTest
一個薄包裝器。 因此,與普通控制器規范不同,沒有直接訪問session
。
因此,不能直接使用AuthLogic
直接登錄用戶, AuthLogic
依賴於會話和cookie:
它首先進行身份驗證,然后設置正確的會話值和cookie以保持會話。
對於請求/集成/ api /功能規范,需要直接在登錄路徑上的請求來在幕后設置正確的會話/ cookie。 然后將使用適當的值發送回集成會話(就像普通的Web請求一樣)。
為了使生活更輕松,您可以添加一個幫助方法,您可以將其包括在請求/集成/ api /功能規范中:
# spec/support/auth_logic_helpers.rb
module Authlogic
module TestHelper
# You can call this anything you want, I chose this name as it was similar
# to how AuthLogic calls it's objects and methods
def create_user_session(user)
# Assuming you have this defined in your routes, otherwise just use:
# '/your_login_path'
post user_session_path, login: user.login, password: user.password
end
end
end
# Make this available to just the request and feature specs
RSpec.configure do |config|
config.include Authlogic::TestHelper, type: :request
config.include Authlogic::TestHelper, type: :feature
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.