gpt4 book ai didi

ruby-on-rails - MiniTest 认证

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

我是 MiniTest 的新手。大多数测试很容易掌握,因为它是 Ruby 代码,并且具有 Rspec 风格的可读性。但是,我在身份验证方面遇到了麻烦。与任何应用程序一样,大多数 Controller 都隐藏在某种身份验证之后,最常见的是 authenticate_user 以确保用户已登录。

如何测试 session -> 用户是否已登录?我正在从头开始使用身份验证,而不是设计。

我确实有这个作为引用:https://github.com/chriskottom/minitest_cookbook_source/blob/master/minishop/test/support/session_helpers.rb

但不太确定如何实现。

让我们以此作为示例 Controller :

class ProductsController < ApplicationController
before_action :authenticate_user

def index
@products = Product.all
end

def show
@product = Product.find(params[:id])
end

end

我的测试在这些基本实例中看起来如何?

test "it should GET products index" do
# insert code to check authenticate_user
get :index
assert_response :success
end

test "it should GET products show" do
# insert code to check authenticate_user
get :show
assert_response :success
end

#refactor so logged in only has to be defined once across controllers.

最佳答案

您是否使用自定义身份验证方法?如果是这样,您可以将所需的 session 变量作为第三个参数传递给请求方法:

get(:show, {'id' => "12"}, {'user_id' => 5})

http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers

否则,如果您使用任何身份验证库,它通常会提供一些辅助方法来进行测试。

关于ruby-on-rails - MiniTest 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34733577/

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