Rspec not logging me in

╄→尐↘猪︶ㄣ 提交于 2020-01-06 14:12:08

问题


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.



来源:https://stackoverflow.com/questions/18564606/rspec-not-logging-me-in

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