Cookies do not persist in Rspec on rails 3.1

前端 未结 3 2027
情歌与酒
情歌与酒 2020-12-06 11:49

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.
相关标签:
3条回答
  • 2020-12-06 12:31

    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.

    0 讨论(0)
  • 2020-12-06 12:33

    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

    0 讨论(0)
  • 2020-12-06 12:45

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

    0 讨论(0)
提交回复
热议问题