diff --git a/spec/json_on_rails/json_attributes_spec.rb b/spec/json_on_rails/json_attributes_spec.rb index 1a8f8ca..cc69843 100644 --- a/spec/json_on_rails/json_attributes_spec.rb +++ b/spec/json_on_rails/json_attributes_spec.rb @@ -109,4 +109,48 @@ end end end + + # Smoke tests, to verify that the default works. + # + context "with Rails-defined defaults" do + # If a plain `{}` (or `[]`) is used as default, it will be shared on each model instantiation. + # + # This can be solved by using: + # + # attribute :extras, ActiveRecord::Type::Json.new, default: -> { {} } + # + # but the following support would be required: + # + # - Type::Json: Proc/Hash/Array in #cast_value; + # - Proc: (Rails) marshalling, in case a dev wants to serialize the instance. + # + # which is not really worth. + # + context "on instantiation" do + it "should set the default" do + user_with_default = WithDefaultUser.new + + expect do + user_with_default.extras["amiga500"] = "awesome" + user_with_default.save! + end.not_to raise_error + end + end + + context "on create!" do + it "should set the default" do + user = WithDefaultUser.create! + + expect { user.extras["amiga500"] = "awesome" }.not_to raise_error + end + + it "should save the value when saving, even when not setting it" do + WithDefaultUser.create! + + user = WithDefaultUser.find_by("extras LIKE ?", {}.to_json) + + expect(user).not_to be(nil) + end + end + end end diff --git a/spec/setup/db/schema.rb b/spec/setup/db/schema.rb index b050995..193882b 100644 --- a/spec/setup/db/schema.rb +++ b/spec/setup/db/schema.rb @@ -1,7 +1,11 @@ # frozen_string_literal: true -ActiveRecord::Schema.define(version: 20180210000000) do +ActiveRecord::Schema.define(version: 20180214000000) do create_table "users" do |t| t.json "extras" end + + create_table "with_default_users" do |t| + t.json "extras" + end end diff --git a/spec/setup/models/with_default_user.rb b/spec/setup/models/with_default_user.rb new file mode 100644 index 0000000..c4eac79 --- /dev/null +++ b/spec/setup/models/with_default_user.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class WithDefaultUser < ActiveRecord::Base + after_initialize do |instance| + instance.extras = {} + end +end