Rails 迷你测试。当 Exception class 是私有的时,检查是否引发异常的正确方法是什么?

Rails MInitest. How's the proper way to check if an exception is raised when the Exception class is private?

我在我的一个模型中定义了一个“私有”异常 class(因为它是一个实现细节):

class User < ApplicationRecord
  class InvalidStateException < StandardError
    def initialize(msg = "Invalid State")
       super(msg)
    end
  end

  private_constant :InvalidStateException
end

在我的测试中,我想检查是否像这样引发异常:

test "should not follow themselves" do
  joao = users(:joao)

  assert_not joao.following?(joao)
  assert_raise(User::InvalidStateException) { joao.follow(joao) }
  assert_not joao.following?(joao)
end

但正如预期的那样,一旦我尝试在测试中引用私有常量,就会引发 NameError:

test_should_not_follow_themselves#RelationshipTest (1.92s)
NameError:         NameError: private constant #<Class:0x00005570b89cba48>::InvalidStateException referenced

那么我怎样才能让异常成为私有的并测试它呢?

我觉得你在做什么counter-intuitive,但我有什么资格评判谁。

ruby 中没有任何内容是真正私有的,您可以使用 .const_get

获取“私有”常量
User.const_get(:InvalidStateException)