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