相关型号:
class User < ActiveRecord::Base
acts_as_authentic
end
class UserSession < Authlogic::Session::Base
endApplicationController:
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这是User的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不为nil。
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如何找到任何东西。
发布于 2014-12-12 06:15:55
我偶然发现了一个类似的问题,当从RSpec请求规范驱动时,UserSession.find在控制器中返回nil。
在RSpec测试之间运行数据库清理器会导致authlogic的UserSession.find (有时)返回nil,即使会话是有效的。我将使用UserSession.create(模型),并且立即,UserSession.find将返回nil。但仅限于请求规格。这是令人沮丧的。
然而,这不是authlogic的错。我在模型类中发现了一个在数据库清理过程中幸存下来的memoization。这维护了一个对活动记录对象的幻影引用,而这个意外传递给UserSession.create的引用导致了这种现象。会话已创建,并且立即不可找到,但仅在数据库清理器运行时才创建。
https://stackoverflow.com/questions/15316557
复制相似问题