gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:33 25 4
gpt4 key购买 nike

我正在测试我的 session Controller ,但出现此错误,登录功能有效,我在浏览器上对其进行了测试,但我是 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)>'

这是我的 Controller 的代码:

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

最佳答案

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

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

关于ruby-on-rails - Rails Rspec - 未定义的方法 `session',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com