跳至内容 跳至搜索

Active Model Lint 测试

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

请注意,对象不必实现所有 API 才能与 Action Pack 配合使用。此模块仅旨在在你想要开箱即用所有功能的情况下提供指导。

这些测试不会尝试确定返回值的语义正确性。例如,你可以实现 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 model.persisted?() false end
  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 model.to_key() [1] end
  def model.persisted?() false end
  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 用于查找部分视图。例如,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