我有一个这样的模型:
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
而不是特定于模型的消息时,这将失败。
那么,有可能检查发生了哪种错误吗?
expect(record.errors).to be_added :name, :blank
。 - PhilTassert record.errors.added?(:slug, :too_short, count: 5)
,其中5是所需的长度。 - Gerry Shawadded?
在内部仍然执行字符串比较错误消息。这意味着我们必须传入插值值才能使其工作: https://github.com/rails/rails/pull/14067/files#r9781601,这有点让人烦恼。 - lulalala