gpt4 book ai didi

ruby-on-rails - 使用 Rspec on Rails 6 测试 Controller 问题

转载 作者:行者123 更新时间:2023-12-04 01:32:49 30 4
gpt4 key购买 nike

我无法在 Controller 问题上使用匿名 Controller 从规范访问 session 或路由路径 (root_url)。

这是我的代码

module SecuredConcern
extend ActiveSupport::Concern

def logged_in?
session[:user_info].present?
end

def redirect_to_login
redirect_to login_path unless logged_in?
end

def redirect_to_home
redirect_to root_path if logged_in?
end
end

和规范

require 'rails_helper'

describe SecuredConcern, type: :controller do
before do
class FakesController < ApplicationController
include SecuredConcern
end
end

after { Object.send :remove_const, :FakesController }
let(:object) { FakesController.new }
# let(:session) {create(:session, user_info: '')}

describe 'logged_in' do
it "should return false if user is not logged in" do
expect(object.logged_in?).to eq(false)
end
end
end

这是痕迹:

Module::DelegationError:
ActionController::Metal#session delegated to @_request.session, but @_request is nil: #<FakesController:0x00007f9856c04c20 @_action_has_layout=true, @rendered_format=nil, @_routes=nil, @_request=nil, @_response=nil>
# ./app/controllers/concerns/secured_concern.rb:9:in `logged_in?'
# ./spec/controllers/concerns/secured_concern_spec.rb:21:in `block (3 levels) in <main>'
# ------------------
# --- Caused by: ---
# NoMethodError:
# undefined method `session' for nil:NilClass
# ./app/controllers/concerns/secured_concern.rb:9:in `logged_in?'

配置更新为 config.infer_base_class_for_anonymous_controllers = true

关于我在这里做错了什么的任何指示?

最佳答案

这是我使用 RSpec.shared_examples 解决它的方法

在我包含此问题的 Controller 规范中:

# spec/controllers/home_controller_spec.rb
RSpec.describe HomeController, type: :controller do
it_behaves_like 'SecuredConcern', HomeController
end

在我的关注规范中:

# spec/shared/secured_concern_spec.rb
require 'rails_helper'

RSpec.shared_examples 'SecuredConcern' do |klass|
describe '#logged_in?' do
it "should return true if user is logged in" do
session[:user_info] = {uid: 1}
expect(subject.logged_in?).to eq(true)
end

it "should return false if user is not logged in" do
expect(subject.logged_in?).to eq(false)
end
end
end

希望对遇到类似问题的人有所帮助。

关于ruby-on-rails - 使用 Rspec on Rails 6 测试 Controller 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533904/

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