mil*_*350 5 ruby testing controller ruby-on-rails minitest
我是MiniTest的新手.大多数测试都很容易掌握,因为它是Ruby代码,并且还具有Rspec风格的可读性.但是,我在身份验证方面遇到了麻烦.与任何应用程序一样,大多数控制器都隐藏在某种身份验证之后,最常见的是authenticate_user确保用户登录.
如何测试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
Run Code Online (Sandbox Code Playgroud)
在这些基本实例中,我的测试如何?
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.
Run Code Online (Sandbox Code Playgroud)
小智 2
您是否使用自定义身份验证方法?如果是这样,您可以将所需的会话变量作为第三个参数传递给请求方法:
get(:show, {'id' => "12"}, {'user_id' => 5})
Run Code Online (Sandbox Code Playgroud)
http://guides.rubyonrails.org/testing.html#function-tests-for-your-controllers
否则,如果您使用任何身份验证库,它通常会提供一些用于测试的辅助方法。
| 归档时间: |
|
| 查看次数: |
835 次 |
| 最近记录: |