首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MiniTest认证

MiniTest认证
EN

Stack Overflow用户
提问于 2016-01-12 00:23:08
回答 2查看 1.3K关注 0票数 5

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

如何测试登录的session ->用户?我是从零开始使用认证,而不是设计。

我确实有这样的参考:helpers.rb

但不太确定如何实现。

让我们将其用作示例控制器:

代码语言:javascript
复制
class ProductsController < ApplicationController
  before_action :authenticate_user

  def index
    @products = Product.all
  end

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

end

在这些基本实例中,我的测试结果如何?

代码语言:javascript
复制
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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-12 03:53:44

您正在使用自定义身份验证方法吗?如果是这样,您可以将所需的会话变量作为第三个param传递给request方法:

代码语言:javascript
复制
get(:show, {'id' => "12"}, {'user_id' => 5})

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

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

票数 2
EN

Stack Overflow用户

发布于 2016-01-12 00:33:24

您需要包括设计测试助手,然后您可以使用devise,就像在控制器中一样。

即:

代码语言:javascript
复制
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)测试控制器

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34733577

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档