Should native validations be tested in rails?

前端 未结 5 2607
醉梦人生
醉梦人生 2021-02-20 07:25

Everybody knows that automated testing is a good thing.

Not everybody knows exacly what to test.

My question is if native validations like validate_presence_of,

5条回答
  •  醉话见心
    2021-02-20 08:16

    Matthew Bass has a great gem he's released for just this type of thing. It adds rspec matchers that check to make sure the validation is in place without actually running the underlying ActiveRecord code. Read more about it here.

    It adds matchers for validations:

    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)
    

    Also matchers for associations:

    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
    

    And a few other useful additions:

    # 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
    

    That's not by any means an exhaustive list. I've got a fork where I've added a few others I needed, likely there are others floating around as well. It's a good approach and for me fit the middle ground between ensuring the validations were still in the model, and having to explicitly write tests to execute ActiveRecord code to ensure it.

提交回复
热议问题