Rspec not logging me in

2019-09-02 10:42发布

问题:

I was looking at this answer to see how to test a session controller and wrote something like this:

require 'spec_helper'

describe SessionsController do
  context "We should login to the system and create a session" do
    let :credentials do
      {:user_name => "MyString", :password => "someSimpleP{ass}"}
    end

    let :user do
      FactoryGirl.create(:user, credentials)
    end

    before :each do
      post :create , credentials
    end

    it "should create a session" do
      puts user.inspect
      puts session[:user_id]
      #session[:user_id].should == user.id
    end
  end
end

Based on that I created a factory girl user:

FactoryGirl.define do
  factory :user, :class => 'User' do
    name "sample_user"
    email "MyString@gmail.com"
    user_name "MyString"
    password "someSimpleP{ass}"
  end
end

Now it all works - exceot for the before :each do statement - it never "logs" the "user" in - thus I cannot test the controllers functionality of, is a session properly created?

Now most would say, use capybara and test it through that way - but that's wrong, IMO - sure if I'm doing front end testing that would work, but I'm testing controller based logic. Can some one tell me why this isn't working? routing works fine.

My puts session[:user_id] is coming up nil, when it shouldn't

回答1:

You misunderstood SessionsController and RegistrationsController.

A Session is for an user who has already registered, not for creating an user. #create in SessionController means to create a session, not an user.

RegistrationController is for creating user with full details including password_confirmation.

To test SessionsController, you need to create a valid user in FactoryGirl at first, then use his credentials say email and password to sign in.



回答2:

let is lazily evaluated, even for the before clause, so the user has not been created as of the time you do the post to login. If you change to using let!, you'll avoid this problem.