Skip to content
This repository has been archived by the owner on Feb 13, 2018. It is now read-only.

Commit

Permalink
Add validations to note model
Browse files Browse the repository at this point in the history
  • Loading branch information
bishboria committed Feb 27, 2014
1 parent 776e9d4 commit f64b487
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
16 changes: 14 additions & 2 deletions app/models/note.rb
Expand Up @@ -9,9 +9,21 @@ class Note

default_scope order_by([:created_at, :desc])

validates_presence_of :text, :need_id, :author
validate :validate_need_id

def save
need = Need.find(need_id)
self.revision = need.revisions.first.id
need = Need.where(need_id: need_id).first
self.revision = need.revisions.first.id if need
super
end

private

def validate_need_id
need = Need.where(need_id: need_id).first
if need.nil?
errors.add(:need_id, "A note must have a valid need_id")
end
end
end
30 changes: 29 additions & 1 deletion test/unit/note_test.rb
Expand Up @@ -15,7 +15,7 @@ class NoteTest < ActiveSupport::TestCase
end

should "be able to create a note" do
Need.expects(:find).returns(@need)
Need.expects(:where).twice.returns([@need])

note = Note.new(@atts)
note.save
Expand All @@ -25,4 +25,32 @@ class NoteTest < ActiveSupport::TestCase
assert_equal "Winston Smith-Churchill", note.author["name"]
assert_equal @need.revisions.first.id.to_s, note.revision
end

should "not save a note without a need_id" do
note = Note.new(@atts.except(:need_id))

refute note.save
assert note.errors.has_key?(:need_id)
end

should "not save a note without a valid need_id" do
note = Note.new(@atts.merge(need_id: :foo))

refute note.save
assert note.errors.has_key?(:need_id)
end

should "not save a note without text" do
note = Note.new(@atts.except(:text))

refute note.save
assert note.errors.has_key?(:text)
end

should "not save a note without an author" do
note = Note.new(@atts.except(:author))

refute note.save
assert note.errors.has_key?(:author)
end
end

0 comments on commit f64b487

Please sign in to comment.