【问题标题】:Authlogic/Rspec/Rails 3.2: UserSession.find returns nil in ApplicationControllerAuthlogic/Rspec/Rails 3.2:UserSession.find 在 ApplicationController 中返回 nil
【发布时间】:2013-03-09 22:18:32
【问题描述】:

相关型号:

class User < ActiveRecord::Base 
    acts_as_authentic
end

class UserSession < Authlogic::Session::Base
end

应用控制器:

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:

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

这是用户的 Rspec 定义:

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 不为零。

UserSession.create(current_user)
just_created_session = UserSession.find

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

感谢任何帮助。

环境

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,它所做的只是:

def create(*args, &block)
    session = new(*args)
    session.save(&block)
    session
end

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

【问题讨论】:

  • 感谢您的回复。我试着摆脱它,但它没有帮助。该方法确实被调用,因为我在那里有一个断点。再深入一点,authlogic 的 persistence.rb 文件有一个叫persisting的方法?最终返回 nil 这是问题所在。
  • 你知道这里发生了什么吗?我遇到了这个问题,它已经耽误了我几个小时。

标签: ruby-on-rails ruby ruby-on-rails-3 factory-bot authlogic


【解决方案1】:

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

在 RSpec 测试之间运行数据库清理程序导致 authlogic 的 UserSession.find(有时)返回 nil,即使会话有效。我会 UserSession.create(model) 并立即 UserSession.find 将返回 nil。但仅来自请求规范。这很令人沮丧。

但是,这不是 authlogic 的错。我在模型类中发现了一个在数据库清理中幸存下来的记忆。这维护了对活动记录对象的幻像引用,而这个引用意外地传递给了 UserSession.create,导致了症状。会话已创建,但立即无法找到,但只有在数据库清理器运行时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多