user502052
user502052

Reputation: 15259

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

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?

Upvotes: 1

Views: 333

Answers (4)

Severin Ulrich
Severin Ulrich

Reputation: 421

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

Upvotes: 0

jake
jake

Reputation: 2411

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.

Upvotes: 3

jefflunt
jefflunt

Reputation: 33954

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

Upvotes: 0

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

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

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

Upvotes: 2

Related Questions