Torstein
Torstein

Reputation: 397

How to use RSpecs valid_session?

I'm having trouble finding examples of valid_session in RSpec, and now all my scaffolded tests are broken after having added authorization.

Going through Michael Hartl's Rails Tutorial, I'm using the authentication which is described here, except I'm requiring login for all pages and use 'skip_before_filter' for signin etc.

I've added a user fixture, which I've verified gets loaded:

userexample:
  id: 1
  name: Example Name
  email: [email protected]
  password_digest: $2a$10$NuWL8f2X0bXaCof3/caiiOwlF2rago7hH10JECmw1p75kEpf0mkie
  remember_token: YXjPrFfsK8SFQOQDEa90ow

Then in the controller spec

def valid_session
    { remember_token: "YXjPrFfsK8SFQOQDEa90ow" }
end

The code of the Session Helper

module SessionsHelper
def sign_in(user)
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
end

def signed_in?
    return !current_user.nil?
end

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

def current_user=(user)
    @current_user = user
end

def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
end

Am I using valid_session as intended? Will supplying a remember_token with the session even work without explicitly signing in the user with sign_in? Could this be solved in some other way?

Upvotes: 5

Views: 3070

Answers (1)

Eric Wanchic
Eric Wanchic

Reputation: 2084

This should work for you...

def valid_session
  controller.stub!(:signed_in?).and_return(true)
end

...based on something similar that worked for me :D

def valid_session
  controller.stub!(:authorize).and_return(User)
end

Upvotes: 3

Related Questions