跳至内容 跳至搜索

Active Model Lint Tests

通过在 TestCase 中包含 ActiveModel::Lint::Tests,您可以测试一个对象是否符合 Active Model API。它将包含一些测试,告诉您对象是否完全符合要求,如果不符合,那么 API 的哪些方面未实现。

请注意,为了与 Action Pack 一起工作,对象并不需要实现所有 API。此模块仅旨在为您提供指导,以防您想要开箱即用所有功能。

这些测试不试图确定返回值的语义正确性。例如,您可以实现 valid? 使其始终返回 true,这样测试就会通过。您需要自己确保这些值在语义上是有意义的。

期望您传入的对象在调用 to_model 时返回一个符合要求的对象。to_model 返回 self 是完全可以的。

方法
T

实例公共方法

test_errors_aref()

如果对象的模型响应 errors 方法,并且调用此方法的结果并使用 [](attribute) 访问时返回一个数组,则测试通过。否则失败。

errors[attribute] 用于检索模型中给定属性的错误。如果存在错误,则该方法应返回一个字符串数组,这些字符串是该属性的错误。如果使用了本地化,字符串应根据当前区域设置进行本地化。如果没有错误,该方法应返回一个空数组。

# File activemodel/lib/active_model/lint.rb, line 102
def test_errors_aref
  assert_respond_to model, :errors
  assert_equal [], model.errors[:hello], "errors#[] should return an empty Array"
end

test_model_naming()

如果对象的模型既作为实例方法也作为类方法响应 model_name,并且调用此方法返回的字符串包含一些便利方法::human:singular:plural,则测试通过。

有关更多信息,请参阅 ActiveModel::Naming

# File activemodel/lib/active_model/lint.rb, line 81
def test_model_naming
  assert_respond_to model.class, :model_name
  model_name = model.class.model_name
  assert_respond_to model_name, :to_str
  assert_respond_to model_name.human, :to_str
  assert_respond_to model_name.singular, :to_str
  assert_respond_to model_name.plural, :to_str

  assert_respond_to model, :model_name
  assert_equal model.model_name, model.class.model_name
end

test_persisted?()

如果对象的模型响应 persisted? 方法,并且调用此方法返回 truefalse,则测试通过。否则失败。

persisted? 用于计算对象的 URL。如果对象未持久化,例如,该对象的表单将路由到创建操作。如果已持久化,则该对象的表单将路由到更新操作。

# File activemodel/lib/active_model/lint.rb, line 70
def test_persisted?
  assert_respond_to model, :persisted?
  assert_boolean model.persisted?, "persisted?"
end

test_to_key()

如果对象的模型响应 to_key 方法,并且在对象未持久化时调用此方法返回 nil,则测试通过。否则失败。

to_key 返回一个 Enumerable,包含模型的所有(主)键属性,并用于生成对象的唯一 DOM ID。

# File activemodel/lib/active_model/lint.rb, line 31
def test_to_key
  assert_respond_to model, :to_key
  def_method(model, :persisted?) { false }
  assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false"
end

test_to_param()

如果对象的模型响应 to_param 方法,并且在对象未持久化时调用此方法返回 nil,则测试通过。否则失败。

to_param 用于在 URL 中表示对象的键。实现者可以选择是引发异常还是在记录使用复合主键时提供默认值。lint 中没有针对此行为的测试,因为将任何可能的实现策略强加给实现者没有意义。

# File activemodel/lib/active_model/lint.rb, line 46
def test_to_param
  assert_respond_to model, :to_param
  def_method(model, :to_key) { [1] }
  def_method(model, :persisted?) { false }
  assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false"
end

test_to_partial_path()

如果对象的模型响应 to_partial_path 方法,并且调用此方法返回一个字符串,则测试通过。否则失败。

to_partial_path 用于查找局部视图(partials)。例如,一个 BlogPost 模型可能会返回 “blog_posts/blog_post”。

# File activemodel/lib/active_model/lint.rb, line 58
def test_to_partial_path
  assert_respond_to model, :to_partial_path
  assert_kind_of String, model.to_partial_path
end