ruby-on-rails – 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设置为测试的模拟控制器: 在我的规范中,我看到@controller是一个Authlogic :: TestCase :: MockController 在我的规范中,我看到Authlogic :: Session :: Base.controller被设置为该Mock控制器. 但是,我检查一下: class ApplicationController < ActionController::Base ... def current_user_session raise Authlogic::Session::Base.controller.inspect ... end end 我看到Authlogic :: ControllerAdapters :: RailsAdapter …所以不知何故控制器正在设置但不持久.我想知道这是否与从Rails3到Rails4的切换有关? 任何洞察这一点将不胜感激. 宝石版本适合那些感兴趣的人: 解决方法
根据
https://stackoverflow.com/a/5803121,请求规范只是
ActionDispatch::IntegrationTest 左右的一个薄包装.因此,与普通的控制器规范不同,没有直接访问会话.
因此,直接使用
对于请求/集成/ api /功能规范,需要直接在登录路径上的请求来在幕后设置正确的会话/ cookie.然后将使用适当的值发送回集成会话(就像普通的Web请求一样). 为了简化生活,您可以添加一个帮助方法,您可以将其包含在请求/集成/ api / feature规范中: # 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |