问题描述
这是以下环境中控制器规范中 cookie 集合的问题:
This is a problem with the cookies collection in a controller spec in the following environment:
- rails 3.1.0.rc4
- rspec 2.6.0
- rspec-rails 2.6.1
我有一个简单的控制器规范,它创建一个工厂用户,调用一个设置 cookie 的登录方法,然后测试登录用户是否可以访问页面.问题是,在设置的身份验证 cookie 和在我的控制器上调用的显示"操作之间,所有 cookie 似乎都消失了.
I have a simple controller spec that creates a Factory user, calls a sign in method which sets a cookie, and then tests to see if the signed in user may access a page. The problem is that all cookies seem to disappear between the authentication cookie being set and the "show" action being called on my controller.
在 Rails 开发服务器上的浏览器中运行时,我的代码运行良好.运行规范时更奇怪的行为是,通过 cookie 散列设置的所有内容都消失了,但通过会话散列设置的所有内容仍然存在.在使用 rspec 时,我是否只是遗漏了 cookie 的工作原理?
My code works fine when run in a browser on the rails dev server. The even stranger behavior while running the spec is that everything set though the cookies hash disappears but everything set through the session hash persists. Am I just missing something about how cookies work when using rspec?
规格代码
it "should be successful" do
@user = Factory(:user)
test_sign_in @user
get :show, :id => @user
response.should be_success
end
登录代码
def sign_in(user, opts = {})
if opts[:remember] == true
cookies.permanent[:auth_token] = user.auth_token
else
cookies[:auth_token] = user.auth_token
end
session[:foo] = "bar"
cookies["blah"] = "asdf"
self.current_user = user
#there are two items in the cookies collection and one in the session now
end
对 get :show 请求的身份验证检查在此处失败,因为 cookie[:auth_token] 为零
Authentication check on the get :show request fails here because cookies[:auth_token] is nil
def current_user
#cookies collection is now empty but session collection still contains :foo = "bar"... why?
@current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
end
这是一个错误吗?这是我不理解的某种预期行为吗?我只是在看一些明显的东西吗?
Is this a bug? Is it some sort of intended behavior that I don't understand? Am I just looking past something obvious?
推荐答案
我是这样解决的:
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
current_user = user
@current_user = user
end
def sign_out
current_user = nil
@current_user = nil
cookies.delete(:remember_token)
end
def signed_in?
return !current_user.nil?
end
出于某种原因,您必须同时设置 @current_user 和 current_user 才能使其在 Rspec 中工作.我不知道为什么,但它让我完全疯了,因为它在浏览器中运行良好.
For some reason you have to set both @current_user and current_user for it to work in Rspec. I'm not sure why but it drove me completely nuts since it was working fine in the browser.
这篇关于Cookie 不会在 Rails 3.1 上的 Rspec 中持续存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!