我是MiniTest的新手。大多数测试都很容易掌握,因为它是Ruby代码,而且还具有Rspec风格的可读性。然而,我在认证方面遇到了困难。与任何应用程序一样,大多数控制器都隐藏在某种身份验证之后,最常见的是确保用户登录的authenticate_user。
如何测试登录的session ->用户?我是从零开始使用认证,而不是设计。
我确实有这样的参考:helpers.rb
但不太确定如何实现。
让我们将其用作示例控制器:
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.发布于 2016-01-12 03:53:44
您正在使用自定义身份验证方法吗?如果是这样,您可以将所需的会话变量作为第三个param传递给request方法:
get(:show, {'id' => "12"}, {'user_id' => 5})http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers
否则,如果您使用任何身份验证库,它通常提供一些用于测试的辅助方法。
发布于 2016-01-12 00:33:24
您需要包括设计测试助手,然后您可以使用devise,就像在控制器中一样。
即:
require 'test_helper'
class ProtectedControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "authenticated user should get index" do
sign_in users(:foo)
get :index
assert_response :success
end
test "not authenticated user should get redirect" do
get :index
assert_response :redirect
end
end还可以查看以下内容:
https://stackoverflow.com/questions/34733577
复制相似问题