Skip to content
Browse files

add specs for base.new? and fix new_record behavior on load with ID

  • Loading branch information...
1 parent 4d9962e commit becc5692a0d83bdfb5cbb0c7b750ecc2812f947b @nickurban nickurban committed Mar 14, 2012
Showing with 34 additions and 4 deletions.
  1. +3 −2 lib/well_rested/base.rb
  2. +31 −2 spec/base_spec.rb
View
5 lib/well_rested/base.rb
@@ -134,8 +134,9 @@ def load(attrs_to_load, from_api = false)
#puts "*** Warning: loading a resource without a schema (#{self.class})!" if schema.nil?
#raise "Tried to load attributes for a resource with no schema (#{self.class})!" if schema.nil?
- # By default we mark a record as new if it doesn't come from the API and it doesn't have an ID attribute.
- self.new_record = !from_api and !attrs_to_load.include?('id')
+ # We mark a record as new if it doesn't come from the API and it doesn't have an ID.
+ self.new_record = !from_api
+ self.new_record = false if attrs_to_load.include?(:id) or attrs_to_load.include?('id')
new_attrs = {}.with_indifferent_access
View
33 spec/base_spec.rb
@@ -160,7 +160,7 @@ class ResourceWithDefaults < Base
end
end
end
-
+
describe ".new_from_api" do
it "should call load_from_api" do
mock = double()
@@ -169,7 +169,10 @@ class ResourceWithDefaults < Base
Base.new_from_api({})
end
- it "should set new_record to false"
+ it "should set new_record to false" do
+ b = Base.new_from_api({})
+ b.new_record.should == false
+ end
end
describe ".load" do
@@ -182,6 +185,32 @@ class ResourceWithDefaults < Base
end
end
+ # It is not new if it was loaded from the API.
+ # If it was loaded locally but has an ID defined, but default it is not considered new either.
+ # This is to support the case where an update call is made by calling Resource.new followed by @api.save(res).
+ # For Rails, we need .new? to return false when rendering a form with an error or else the form will not have _method => PUT.
+ describe ".new?" do
+ before { @obj = Base.new }
+ subject { @obj.new? }
+ context "when called with from_api as true and without an ID" do
+ before { @obj.load({:x => 1}, true) }
+ it { should be_false }
+ end
+ context "when called with from_api as true and with an ID" do
+ before { @obj.load({:id => 1}, true) }
+ it { should be_false }
+ end
+ context "when called with from_api as false and with an ID" do
+ before { @obj.load({:id => 1}, false) }
+ it { should be_false }
+ end
+ # Only case where it is considered new by default.
+ context "when called with from_api as false and without an ID" do
+ before { @obj.load({:x => 1}, false) }
+ it { should be_true }
+ end
+ end
+
describe ".load_for_api" do
it "should call .load with from_api true" do
obj = Base.new

0 comments on commit becc569

Please sign in to comment.
Something went wrong with that request. Please try again.