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

标签 ruby-on-rails ruby rspec-rails ruby-on-rails-6 activesupport-concern

我无法在 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/

相关文章:

ruby-on-rails - 如何使用 Rspec 测试强参数?

ruby-on-rails - 使用 RSpec : setting locale based on first subdomain 进行测试

ruby-on-rails - 使用 rvm1-capistrano3 安装 Ruby

javascript - 如何集成jquery.fileupload-rails?

ruby - 如何在 Sinatra 中制作一个发布按钮

ruby - 使用 AES 的 Rails 加密,过于复杂

ruby-on-rails - ActionController::UrlGenerationError,没有路由匹配

css - Rails select_tag css 与 options_from_collection_for_select

ruby-on-rails - 如何让两个 Elastic Beanstalk 环境共享一个数据库实例

ruby - 在扫描或正则表达式模式中的模式中提取 Ruby 字符串