Home > Articles

This chapter is from the book

This chapter is from the book

8.9 Testing Validations with Shoulda

Even though validations are declarative code, if you’re doing TDD then you’ll want to specify them before writing them. Luckily, Thoughtbot’s Shoulda Matchers library3 contains a number of matchers designed to easily test validations.

describe Post do
  it { should validate_uniqueness_of(:title) }
  it { should validate_presence_of(:body).with_message(/wtf/) }
  it { should validate_presence_of(:title) }
  it { should validate_numericality_of(:user_id) }
end

describe User do
  it { should_not allow_value("blah").for(:email) }
  it { should_not allow_value("b lah").for(:email) }
  it { should allow_value("a@b.com").for(:email) }
  it { should allow_value("asdf@asdf.com").for(:email) }
  it { should ensure_length_of(:email).is_at_least(1).is_at_most(100) }
  it { should ensure_inclusion_of(:age).in_range(1..100) }
end

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.