2016-01-12 250 views
4

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

如何测试session - >用户已登录?我从头开始不使用身份验证。

我有这个作为参考: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. 

回答

1

是否使用自定义的验证方法? 如果是这样,你可以根据需要通过会话变量作为第三个参数去请求方法:

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

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

否则,如果你使用任何身份验证库通常为测试了一些辅助方法。

+0

对于索引页怎么样? – miler350

+0

我不'看到任何区别'get(:index,{},{'user_id'=> 5})' – Oleg

2

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

即:

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 

还检查了这一点:
How To: Test controllers with Rails 3 and 4 (and RSpec)

+0

我不使用设计。对不起,忘了在我的文章中指定。 – miler350

+1

in rails 5它是'include Devise :: Test :: IntegrationHelpers' – thedanotto