【问题标题】:Ruby on Rails Testing With Devise Authorization Helpers, Wrong Number of Arguments in Test Helper使用设计授权助手进行 Ruby on Rails 测试,测试助手中的参数数量错误
【发布时间】:2021-11-08 22:11:59
【问题描述】:

我有一个基本的 Rails Scaffold,所有控制器操作都受到过滤器的保护,该过滤器确定当前用户是否是管理员。我决定创建一个帮助程序来登录用户并断言响应,而不是在每个控制器测试期间登录管理员和非管理员用户。所有控制器测试都正常工作,但我的辅助函数中出现了一个奇怪的参数错误数量错误(如下所示)。

控制器sn-p:

class QuotesController < ApplicationController
  before_action :set_quote, only: [:show, :edit, :update, :destroy]
  before_action :admin_filter

  # GET /quotes
  def index
    @quotes = Quote.all
  end
#... rest of actions...
  private
   # Returns true if user is admin
  def is_admin?
    current_user.boss if user_signed_in?
  end

  # Redirect If not Admin
  def admin_filter
    redirect_to root_path unless is_admin?
  end
end

测试助手(减少登录和注销用户的冗余):

# test_helper.rb
class ActiveSupport::TestCase
  include Devise::Test::IntegrationHelpers

  # Add more helper methods to be used by all tests here...
  module AuthTesting

    # compacts admin_access and unsigned_no_admin to one test
    def test_authorization(path, admin, non_admin) # Error @ this line, stacktrace ends 
      admin_access(path, admin)
      unsigned_no_admin_no_access(path, non_admin)
    end

    # asserts redirect for not signed in/ non admin users
    def unsigned_no_admin_no_access(path, non_admin)
      get path
      assert_response :redirect
      sign_in non_admin
      get path
      assert_response :redirect
      sign_out non_admin
    end

    # Asserts that admin has access 
    def boss_access(path, admin)
      sign_in admin
      get path
      assert_response :success
      sign_out admin # prevents test_access from having leftover signed in admin
    end

  end
end

测试片段(所有控制器操作正常工作并通过测试)

class QuotesControllerTest < ActionDispatch::IntegrationTest
  include AuthTesting

  setup do
    @quote = quotes(:one)
    @admin = users :jack
    @non_admin = users :phil
  end

  test 'should get index only if admin' do
    test_authorization(quotes_path, @admin, @non_admin) # green
  end
#... rest of test ...
end

运行我的测试时的错误:

ERROR["test_authorization", #<Minitest::Reporters::Suite:0x00007f8f009fa7e0 @name="QuotesControllerTest">, 0.3059480000000008]
 test_authorization#QuotesControllerTest (0.31s)
Minitest::UnexpectedError:         ArgumentError: wrong number of arguments (given 0, expected 3)
            test/test_helper.rb:20:in `test_authorization'

为什么我收到此错误但我的所有测试仍然正常工作?我没有正确创建测试助手吗?

【问题讨论】:

    标签: ruby-on-rails ruby testing devise integration-testing


    【解决方案1】:

    不要以test_ 开头帮助方法的名称。

    这是 Minitest 中的约定:以test_ 开头的所有内容都是测试。所以它会被这样调用,没有参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多