Agile Web Development with Rails, Edition 4

Agile Web Development with Rails, Edition 4

7.2 Iteration B2: Unit Testing 6.3 Playtime

7.1 Iteration B1: Validate!

Augment the model with a few vailidity checks.

Various validations: required, numeric, positive, and unique

edit app/models/product.rb
class Product < ActiveRecord::Base
  validates :title, :description, :image_url, :presence => true
  validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
  validates :title, :uniqueness => true
  validates :image_url, :allow_blank => true, :format => {
    :with    => %r{\.(gif|jpg|png)$}i,
    :message => 'must be a URL for GIF, JPG or PNG image.'
  }
end

Demonstrate failures.

get /products/new

New product





Back
post /products

New product

4 errors prohibited this product from being saved:

  • Title can't be blank
  • Description can't be blank
  • Image url can't be blank
  • Price must be greater than or equal to 0.01




Back

Demonstrate more failures.

get /products/new

New product





Back
post /products

New product

1 error prohibited this product from being saved:

  • Price is not a number




Back
edit app/models/product.rb
class Product < ActiveRecord::Base
  validates :title, :description, :image_url, :presence => true
  validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
  validates :title, :uniqueness => true
  validates :image_url, :format => {
    :with    => %r{\.(gif|jpg|png)$}i,
    :message => 'must be a URL for GIF, JPG or PNG image.'
  }
end
pub depot_b

7.2 Iteration B2: Unit Testing 6.3 Playtime