首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Authlogic/Rspec/Rails3.2: ApplicationController中的UserSession.find返回nil

Authlogic/Rspec/Rails3.2: ApplicationController中的UserSession.find返回nil
EN

Stack Overflow用户
提问于 2013-03-10 06:18:33
回答 1查看 997关注 0票数 2

相关型号:

代码语言:javascript
复制
class User < ActiveRecord::Base 
    acts_as_authentic
end

class UserSession < Authlogic::Session::Base
end

ApplicationController:

代码语言:javascript
复制
class ApplicationController < ActionController::Base
    helper :all
    protect_from_forgery
    helper_method :current_user_session, :current_user

    private

    def current_user_session
        return @current_user_session if defined?(@current_user_session)
        @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.record
    end
end

下面是Rspec:

代码语言:javascript
复制
describe "Rate Function" do
    include Authlogic::TestCase
    before(:each) do
        current_user = FactoryGirl.create(:user, persistence_token: "pt", email: "new@example.com", password: 'password', password_confirmation: 'password')
        activate_authlogic
        UserSession.create(current_user)
    end
    it "Some test for rating..." do
        get "/reviews/rate", {:format => :json, :vehicle_id => 3}
        # other stuff here, doesn't matter what it is because it never gets here
    end
    after(:each) do
    end
end

这是User的Rspec定义:

代码语言:javascript
复制
FactoryGirl.define do
    factory :user do
        email "email@example.com"
        password "password"
        password_confirmation "password"
        persistence_token "pertoken"
    end
end

问题是,每次我从任何控制器方法调用current_user时,它总是返回nil,这是因为UserSession.find总是在ApplicationController中返回nil

有趣的是,如果我在Rspec中(而不是在控制器中)运行以下命令,UserSession.find将正常工作,并且just_created_session不为nil。

代码语言:javascript
复制
UserSession.create(current_user)
just_created_session = UserSession.find

所以这个问题是特定于在控制器中调用UserSession.find的。

任何帮助都是非常感谢的。

环境

代码语言:javascript
复制
Ruby: 1.9.3p392
Rails: 3.2.12
Authlogic: 3.2.0
Factory Girl: 4.2.0
Rspec: 2.13.0
OS: Windows 7

更新:我查看了UserSession.create,它所做的一切就是:

代码语言:javascript
复制
def create(*args, &block)
    session = new(*args)
    session.save(&block)
    session
end

由于我在从规范调用时甚至没有存储返回值,该方法似乎也没有进行任何存储,所以我不确定我们希望User.find如何找到任何东西。

EN

回答 1

Stack Overflow用户

发布于 2014-12-12 06:15:55

我偶然发现了一个类似的问题,当从RSpec请求规范驱动时,UserSession.find在控制器中返回nil。

在RSpec测试之间运行数据库清理器会导致authlogic的UserSession.find (有时)返回nil,即使会话是有效的。我将使用UserSession.create(模型),并且立即,UserSession.find将返回nil。但仅限于请求规格。这是令人沮丧的。

然而,这不是authlogic的错。我在模型类中发现了一个在数据库清理过程中幸存下来的memoization。这维护了一个对活动记录对象的幻影引用,而这个意外传递给UserSession.create的引用导致了这种现象。会话已创建,并且立即不可找到,但仅在数据库清理器运行时才创建。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15316557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档