如何测试该验证失败的ActiveRecord的? [英] How to test which validation failed in ActiveRecord?
问题描述
我有这样一个模型:
class User < ActiveRecord::Base
validates_length_of :name, :in => (2..5)
end
我想测试这个验证:
I want to test this validation:
it "should not allow too short name" do
u = User.new(:name => "a")
u.valid?
u.should have(1).error_on(:name)
end
但后来它不检查哪些类型的错误被设置了名称
。我想知道,如果它是 too_short
, too_long
,或者一些其他的验证失败。
But then it does not test which kind of error was set on name
. I want to know, if it was too_short
, too_long
, or maybe some other validation failed.
我可以查找中的错误数组消息文本中,像这样的:
I can lookup the message text in errors array, like this:
u.errors[:name].should include(I18n.t("activerecord.errors.models.user.attributes.name.too_short"))
但是,当我在语言环境文件,而不是特定型号的消息集 activerecord.errors.messages.too_short
这将失败。
那么,是不是可以检查哪些类型的错误发生?
So, is it possible to check which kind of error occured?
推荐答案
我真的不喜欢寻找错误散列翻译的错误消息的想法。有一个老乡Ruby专家交谈后,我最终猴子补丁错误哈希,所以它首先节省了非翻译的消息。
I really don't like the idea of looking for translated error messages in Errors hash. After a conversation with a fellow Rubyists, I ended monkey patching Errors hash, so it saves the non-translated message first.
module ActiveModel
class Errors
def error_names
@_error_names ||= { }
end
def add_with_save_names(attribute, message = nil, options = {})
message ||= :invalid
if message.is_a?(Proc)
message = message.call
end
error_names[attribute] ||= []
error_names[attribute] << message
add_without_save_names(attribute, message, options)
end
alias_method_chain :add, :save_names
end
end
然后你可以测试这样的:
Then you can test like this:
u = User.new(:name => "a")
u.valid?
u.errors.error_names[:name].should include(:too_short)
这篇关于如何测试该验证失败的ActiveRecord的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!