是否应在rails中测试本机validation?

大家都知道自动化测试是件好事。

不是每个人都知道要测试什么。

我的问题是,是否应在应用程序中测试validate_presence_of,validate_uniqueness_of等本机validation。

在我的办公室,我们三个人,一个人认为应该进行测试,一个人认为不应该这样,我在空中。

是。

测试模型属性是否存在仅测试validates_presence_of代码作为真实测试的副产品,即模型中存在validates_presence_of。

如果某人注释掉了一堆validation码,然后忘记取消注释,那么这将无法检测到,并可能导致各种问题。

我测试它们,不是因为我认为它们不起作用,而是确保它们在需要时存在于我的模型中。

Matthew Bass有一个伟大的gem,他已经发布了这种类型的东西。 它添加了rspec匹配器,用于检查以确保validation到位,而无需实际运行基础ActiveRecord代码。 在这里阅读更多相关信息 。

它添加了validation匹配器:

it_should_validate_presence_of :first_name, :last_name, :email it_should_validate_numericality_of :zip it_should_validate_uniqueness_of :email it_should_validate_inclusion_of :gender, :in => %w(Male Female) 

协会的匹配者:

 it_should_belong_to :employer it_should_have_many :friends, :romans, :countrymen it_should_have_one :account it_should_have_and_belong_to_many :comments 

还有一些其他有用的补充:

 # tests that User.count increases by 1 it_should_be_createable :with => {:first_name => 'Ed', :last_name => 'The Duck', :email => 'a@b.com'} # tests that the attribute is protected it_should_protect :email 

这绝不是一份详尽无遗的清单。 我有一个叉子,我已经添加了一些我需要的其他东西,可能还有其他人也在附近。 这是一个很好的方法,对于我来说,在确保validation仍然在模型中,并且必须显式编写测试以执行ActiveRecord代码以确保它之间的中间位置。

这就是像Shoulda这样的工具真正派上用场的地方。 我认为完全由您来测试如何使用人们为您提供的工具编写代码。 仅仅因为你使用has_many,并不意味着你正在使用它!

说真的,如果你将Shoulda整合到混合中,测试这些东西就变得微不足道了。 如果你运行rcov,它会告诉你你写的所有代码都没有经过全面测试,除非你这样做。

您是否计划为每个Ruby运算符和API方法编写unit testing?

您的unit testing应该测试您自己的代码,而不是其他人 – 这是他们的工作,为什么要复制他们的工作? 如果你不相信他们能够很好地完成他们的工作,你为什么要使用他们的代码呢?

测试你写的代码。 ActiveRecord具有很好的测试覆盖率,包括validation类方法的覆盖范围。

规格:

 require 'spec_helper' describe User do before(:each) do @user = User.new end it "should not be valid without an email" do @user.save.should be_false @user.should_not be_valid @user.email = "example@example.com" @user.should be_valid @user.save.should be_true end end 

要获得该规范,您需要

 class User < ActiveRecord::Base validates_presence_of :email end