我有这样一个模型:
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_short
、too_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/