开发者

What "validation logic" should I test?

I am using Ruby on Rails 3.0.9 and RSpec 2. I would like to know what "validation logic" I should test. That is, if in my model I have:

class User < ActiveRecord::Base
  validates :firstname
    :presence => true
end
开发者_如何学Python

What should I test of the following?

  1. "should have a valid first name"
  2. "should not have a valid first name"

Or should I test both?


You can test both by simply doing this:

it "should validate presence of" do
   should validate_presence_of :firstname
end

Take a look at the shoulda matchers for all such standard Rails Validation.


I think you should not test both. This will be enough:

describe User do
  it { should validate_presence_of(:firstname) }
end


There is basically no algorithm for validating names, because the form of names is incredibly culture-centric. So, really you should avoid complex validations for something like a person's name. Some places/cultures don't have last names, for example, so even validating their presence isn't proper. There's a whole list of other examples that make validating names a really bad idea. For more information on the issue of validating names itself, see my answer to this question.

That being said, in general, when validating any field, I test both valid and invalid data. I make sure that, when I set a field to a valid value, that the .valid? method returns true, and when it's invalid, that it returns false.

Typically you don't need to do a long list, you just need to test

  • A typical valid and invalid example
  • A few edge cases


you can also test for specific values:

describe User do    
    context "validations" do
        it { should_not allow_value("admin").for(:firstname) }
        it { should allow_value("JohnDoe").for(:firstname) }
    end    
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜