require 'assert' require 'mr/json_field/record' require 'ardb/record_spy' require 'much-plugin' require 'mr/json_field' require 'mr/model' module MR::JsonField::Record class UnitTests < Assert::Context desc "MR::JsonField::Record" subject{ MR::JsonField::Record } should "use much-plugin" do assert_includes MuchPlugin, subject end end class MixinTests < UnitTests desc "when mixed in" setup do @record_class = Ardb::RecordSpy.new do include MR::JsonField::Record attr_accessor :hash_data_json, :array_data_json end end subject{ @record_class } should "add a before save callback" do callback = subject.callbacks.find{ |c| c.type == :before_save } assert_equal :json_field_sync_all_json_fields_on_save, callback.args.first end end class InitTests < MixinTests desc "and init" setup do @model_class = Class.new do include MR::Model field_accessor :hash_data_json, :array_data_json include MR::JsonField json_field :hash_data json_field :array_data end @record_class.model_class = @model_class @record = @record_class.new @model = @record.model end subject{ @record } should "sync all of its json fields on save" do @model.hash_data = { Factory.string => Factory.string } @model.array_data = Factory.integer(3).times.map{ Factory.string } # since we used the writer the fields and their source should be equal assert_equal @model.hash_data, MR::JsonField.decode(subject.hash_data_json) assert_equal @model.array_data, MR::JsonField.decode(subject.array_data_json) @model.hash_data[Factory.string] = Factory.string @model.array_data << Factory.string # since we modified the fields and didn't use the writer, their source # should not be equal assert_not_equal @model.hash_data, MR::JsonField.decode(subject.hash_data_json) assert_not_equal @model.array_data, MR::JsonField.decode(subject.array_data_json) subject.instance_eval{ json_field_sync_all_json_fields_on_save } # now that the callback has been run they should be equal once again assert_equal @model.hash_data, MR::JsonField.decode(subject.hash_data_json) assert_equal @model.array_data, MR::JsonField.decode(subject.array_data_json) end end end