ruby-on-rails - 如何测试 ActiveRecord 中哪个验证失败?

标签 ruby-on-rails testing activerecord rspec validation

我有这样一个模型:

class User < ActiveRecord::Base
  validates_length_of :name, :in => (2..5)
end

我想测试这个验证:

it "should not allow too short name" do
  u = User.new(:name => "a")
  u.valid?
  u.should have(1).error_on(:name)
end

但是它不会测试在 name 上设置了哪种错误。我想知道它是 too_shorttoo_long 还是其他一些验证失败。

我可以在错误数组中查找消息文本,如下所示:

u.errors[:name].should include(I18n.t("activerecord.errors.models.user.attributes.name.too_short"))

但是当我在语言环境文件中设置 activerecord.errors.messages.too_short 而不是特定于模型的消息时,这将失败。

那么,是否可以检查发生了哪种错误?

最佳答案

rails added an method to query for errors to ActiveModel in late 2011 and Rails v3.2 .只需检查相应的错误是否已#added? :

# An error added manually
record.errors.add :name, :blank
record.errors.added? :name, :blank # => true

# An error added after validation
record.email = 'taken@email.com'
record.valid? # => false
record.errors.added? :email, :taken, value: 'taken@email.com' # => true

请注意,对于参数化的验证(例如 :greater_than_or_equal_to),您还需要传递参数值。

record.errors.add(:age, :greater_than_or_equal_to, count: 1)
record.errors.added?(:age, :greater_than_or_equal_to, count: 1)

错误由它们的 i18n 键标识。您可以在相应的 Rails i18n 中找到相应的 key 来 checkin error section 下任何语言的文件.

您可以问 ActiveModel#Error 的其他一些有趣问题是 #empty?#include?(attr) ,以及任何您可以询问 Enumerable 的问题.

关于ruby-on-rails - 如何测试 ActiveRecord 中哪个验证失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4119379/

相关文章:

ruby-on-rails - 嵌套属性显示页面中的 Rails 表单

language-agnostic - 如何测试矩阵是否是对角线?

reactjs - 在 Docker 中运行时出现 Cypress 错误 "The automation client disconnected. Cannot continue running tests."

testing - NestJs - Jest - 测试 : ConnectionNotFoundError: Connection "default" was not found

ruby-on-rails - Rails ActiveRecord : Skip validations for associations

nhibernate - 使用 ActiveRecord 在 nHibernate 中急切加载延迟加载的实体

ruby-on-rails - Admin 中的 NameError::ResidentsController#destroy Rails

ruby-on-rails - 如何使用来自 git hook post-receive 的特定 rvm gemset 进行 bundle 安装?

ruby-on-rails - rails 4 : making the first user an admin?

ruby-on-rails - ruby /rails : Obtain list of all available imap folders