小型测试身份验证

5
我是新手,刚开始使用MiniTest。大多数测试很容易理解,因为它是Ruby代码,也具有类似于Rspec的可读性。然而,我在身份验证方面遇到了麻烦。与任何应用程序一样,大多数控制器都隐藏在某种身份验证后面,最常见的是authenticate_user以确保用户已登录。
如何测试session -> user是否已登录? 我正在使用自定义身份验证,而不是devise。
我有这个作为参考:https://github.com/chriskottom/minitest_cookbook_source/blob/master/minishop/test/support/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.
2个回答

2

您需要包含Devise测试助手,然后就可以像在控制器中一样使用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

同时也请查看以下内容:
如何使用Rails 3和4(以及RSpec)测试控制器


我没有使用Devise。抱歉,在我的帖子中忘记指定了。 - miler350
1
在 Rails 5 中,它是 include Devise::Test::IntegrationHelpers - thedanotto

2

那么对于索引页面呢? - miler350
我看不出任何区别 get(:index, {}, {'user_id' => 5}) - Oleg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接