gpt4 book ai didi

ruby-on-rails - 配置Warden以在RSpec Controller 规范中使用

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

我能够使用Devise的sign_in方法登录我的 Controller 规格中的用户。但是,既然我要从应用程序中删除Devise,我现在还不确定如何单独使用Warden来获得类似的功能。

我应该如何设置spec/spec_helper.rb和相关的spec/support/*.rb文件,以使Warden在 Controller 规格中充分运行?

我尝试在spec/support/warden.rb上设置包含以下内容的文件:

RSpec.configure do |config|
config.include Warden::Test::Helpers

config.after do
Warden.test_reset!
end
end

然后,我有类似的 before调用来认证 user工厂:
before { login_as FactoryGirl.create(:user) }

但是,这是我一直看到的错误:
NameError:
undefined method `user' for nil:NilClass

此错误可追溯到 Controller 中的 authenticate_user!方法:
def authenticate_user!
redirect_to login_path, notice: "You need to sign in or sign up before continuing." if env['warden'].user.nil?
end

我会很感激任何人都可以提供的指导。

最佳答案

您尝试执行的操作存在一个基本问题。 Warden是Rack中间件,但是RSpec Controller 规范甚至不包括Rack,因为这些类型的规范并不是要运行完整的应用程序堆栈,而只是要运行 Controller 代码。您可以使用单独的测试来测试中间件,但是在这种情况下,我认为测试Warden本身是否有效没有意义。

要测试您是否正确配置了Warden,应使用请求规格或集成规格( cucumber , capybara 或类似规格)。

尽管从技术上讲可以模仿Warden Controller 规范,但我认为在显着增加测试代码的复杂性的同时,并不能给您带来太多好处。请记住,Rack中间件旨在以透明的方式运行,因此您可以轻松地随心所欲地交换中间件。实际上,您的 Controller 完全不应直接依赖于Warden(也许除了ApplicationController之外),因此对您的 Controller 具有对Warden的测试依赖性是封装破坏的迹象。

我最近也遇到过同样的问题,因此希望此评论有用。

关于ruby-on-rails - 配置Warden以在RSpec Controller 规范中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13420923/

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