2013-03-09 47 views
1

相關機型:Authlogic/Rspec的/ Rails的3.2:UserSession.find回報ApplicationController中無

class User < ActiveRecord::Base 
    acts_as_authentic 
end 

class UserSession < Authlogic::Session::Base 
end 

的ApplicationController:

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: "[email protected]", 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 protected]" 
     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找到任何東西。

+0

感謝您的回覆。我試圖擺脫它,但它沒有幫助。該方法確實被調用,因爲我有一個斷點。更深層次看,authlogic的persistence.rb文件有一個名爲persisting的方法?最終返回零這是問題。 – Nightwolf 2013-03-09 23:34:35

+0

你知道這裏發生了什麼嗎?我遇到了這個問題,它已經拖延了好幾個小時。 – sscirrus 2013-11-13 00:52:27

回答

0

我偶然發現了一個類似的問題,當從RSpec請求規範驅動時,UserSession.find在控制器中返回nil。

在RSpec測試之間運行數據庫清理器會導致authlogic的UserSession.find(有時)返回nil,即使會話有效。我會UserSession.create(模型),並立即,UserSession.find將返回零。但僅限於請求規格。這令人沮喪。

但是,這不是authlogic的錯。我發現模型類中的備忘錄正在數據庫清理中倖存下來。這保持了對活動記錄對象的幻影引用,並且此引用意外傳遞給UserSession.create,導致了症狀。該會話已創建,並且立即無法顯示,但僅在數據庫清理程序運行時纔會顯示。