Rails Rspec - 未定义的方法`session'

时间:2015-10-18 18:06:38

标签: ruby-on-rails ruby session rspec

我正在测试我的会话控制器,但是我得到了这个错误,登录功能正常工作,我在浏览器上测试了它但是我刚接触Rspec测试并且无法使其工作

 Failure/Error: expect(response.session[:user_id]).to eq(@user_attr.id)
 NoMethodError:
   undefined method `session' for #<ActionController::TestResponse:0xd30df10>
 # ./spec/controllers/sessions_controller_spec.rb:20:in `block (3 levels) in <top (required)>'

这是我的控制器的代码:

def new
    @user = User.new
end

def create
    @user = User.find_by(username: params[:user][:username])
    if @user && @user.authenticate(params[:user][:password])
        session[:user_id] = @user.id
        redirect_to root_path
    else
        render :new
    end
end

Rspec代码:

require 'rails_helper'

RSpec.describe SessionsController, type: :controller do
describe "get Login page" do
    it "returns http status" do
        get :new
        expect(response).to have_http_status(:success)
    end
end

describe "session" do
    before(:each) do
        @user = FactoryGirl.create(:user)
        @user_attr = FactoryGirl.attributes_for(:user) 
    end

    it "gives session" do
        request.session[:user_id] = nil
        post :create, user: @user_attr
        expect(response.session[:user_id]).to eq(@user_attr.id)
    end
end
end

1 个答案:

答案 0 :(得分:6)

session是一个没有请求/响应上下文的变量,如示例所示。如果你想操纵它或检查它包含的值,你可以简单地做这样的事情:

it "gives session" do
    session[:user_id] = nil
    post :create, user: @user_attr
    expect(session[:user_id]).to eq(@user_attr.id)
end