[英]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.