diff --git a/lib/couchrest/core/model.rb b/lib/couchrest/core/model.rb
index fa3692e..930cbc9 100644
--- a/lib/couchrest/core/model.rb
+++ b/lib/couchrest/core/model.rb
@@ -459,6 +459,12 @@ module CouchRest
update
end
end
+
+ # Saves the document to the db using create or update. Raises an exception
+ # if the document is not saved properly.
+ def save!
+ raise "#{self.inspect} failed to save" unless self.save
+ end
# Deletes the document from the database. Runs the :delete callbacks.
# Removes the _id and _rev fields, preparing the
diff --git a/spec/couchrest/core/model_spec.rb b/spec/couchrest/core/model_spec.rb
index e981778..36c2aa3 100644
--- a/spec/couchrest/core/model_spec.rb
+++ b/spec/couchrest/core/model_spec.rb
@@ -3,6 +3,16 @@ require File.dirname(__FILE__) + '/../../spec_helper'
class Basic < CouchRest::Model
end
+class BasicWithValidation < CouchRest::Model
+
+ before :save, :validate
+ key_accessor :name
+
+ def validate
+ throw(:halt, false) unless name
+ end
+end
+
class WithTemplate < CouchRest::Model
unique_id do |model|
model['important-field']
@@ -299,6 +309,21 @@ describe CouchRest::Model do
@obj['couchrest-type'].should == 'Basic'
end
end
+
+ describe "saving a model with validation hooks added as extlib" do
+ before(:all) do
+ @obj = BasicWithValidation.new
+ end
+
+ it "save should return false is the model doesn't save as expected" do
+ @obj.save.should be_false
+ end
+
+ it "save! should raise and exception if the model doesn't save" do
+ lambda{ @obj.save!}.should raise_error("#{@obj.inspect} failed to save")
+ end
+
+ end
describe "saving a model with a unique_id configured" do
before(:each) do