相关疑难解决方法(0)

如何测试ActiveRecord中哪些验证失败?

我有这样的模型:

class User < ActiveRecord::Base
  validates_length_of :name, :in => (2..5)
end
Run Code Online (Sandbox Code Playgroud)

我想测试一下这个验证:

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

但是它没有测试设置了哪种错误name.我想知道,如果是too_short,too_long,或者一些其它的验证失败.

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

u.errors[:name].should include(I18n.t("activerecord.errors.models.user.attributes.name.too_short"))
Run Code Online (Sandbox Code Playgroud)

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

那么,是否可以检查出现了哪种错误?

testing validation activerecord rspec ruby-on-rails

26
推荐指数
4
解决办法
2万
查看次数

标签 统计

activerecord ×1

rspec ×1

ruby-on-rails ×1

testing ×1

validation ×1