Mus*_*ify 5 rspec ruby-on-rails authlogic rspec2 ruby-on-rails-4
使用Rails 4,我在让Authlogic看到我伪造的UserSession时遇到问题.
我已经设置了#whoami页面来呈现当前用户的电子邮件地址,这是一个简单的测试.
class PagesController < ApplicationController
# before_filter :require_user
def whoami
render :text => current_user.try(:email) || 'anonymous'
end
end
Run Code Online (Sandbox Code Playgroud)
在spec/spec_helper.rb中:
require "authlogic/test_case"
include Authlogic::TestCase
Run Code Online (Sandbox Code Playgroud)
和我的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
Run Code Online (Sandbox Code Playgroud)
我更新了我的应用程序控制器以显示当前会话:
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
Run Code Online (Sandbox Code Playgroud)
使用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被设置为该Mock控制器.
但是,我检查一下:
class ApplicationController < ActionController::Base
...
def current_user_session
raise Authlogic::Session::Base.controller.inspect
...
end
end
Run Code Online (Sandbox Code Playgroud)
我看到Authlogic :: ControllerAdapters :: RailsAdapter ...所以不知何故控制器正在设置但不持久.我想知道这是否与从Rails3到Rails4的切换有关?
任何洞察这一点将不胜感激.
对于那些感兴趣的宝石版本:gem rspec-core(2.14.5)gem authlogic(3.3.0)gem rails(4.0.0)
根据/sf/answers/406218501/,请求规范只是一个薄的包装ActionDispatch::IntegrationTest.因此session,与普通控制器规范不同,没有直接访问.
因此,直接登录用户是不可能的AuthLogic,这依赖于会话和cookie:
它首先进行身份验证,然后设置正确的会话值和cookie以保持会话.
对于请求/集成/ 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2442 次 |
| 最近记录: |