Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic validations for Product slugs #169

Merged
merged 1 commit into from
Nov 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions spec/example_app/app/models/product.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ class Product < ActiveRecord::Base
validates :image_url, presence: true
validates :name, presence: true
validates :price, presence: true
validates :slug, uniqueness: true
validate :valid_slug

def to_s
name
Expand All @@ -16,4 +18,10 @@ def name=(value)
def to_param
slug
end

def valid_slug
if slug.blank?
errors.add :name, "must have letters or numbers for the URL"
end
end
end
15 changes: 15 additions & 0 deletions spec/models/product_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,20 @@
it { should validate_presence_of(:image_url) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:price) }

it "should not allow names that produce empty slugs" do
product = build(:product, name: "???")

product.validate

expect(product.errors[:name]).
to include("must have letters or numbers for the URL")
end

context "with other products in the database" do
subject { build(:product) }

it { should validate_uniqueness_of(:slug) }
end
end
end