Cookies do not persist in Rspec on rails 3.1

淺唱寂寞╮ 提交于 2019-11-27 23:52:45

This is how I solved this:

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

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.

Ran into the same problem. Try using @request.cookie_jar from your tests.

The extra lines above are not necessary. I found that simply calling the self.current_user = user setter method can automatically update the instance variable. For some reason, calling it without self doesn't call the setter method.

Here's my code without the extra lines:

def sign_in(user)
  cookies.permanent.signed[:remember_token] = [user.id, user.salt]
  self.current_user = user
end

def sign_out
  cookies.delete(:remember_token)
  self.current_user = nil
end

def current_user=(user)
  @current_user = user
end

I still don't know why, maybe an Rspec bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!