diff --git a/lib/activeuuid/uuid.rb b/lib/activeuuid/uuid.rb index 48b40c6..8e59862 100644 --- a/lib/activeuuid/uuid.rb +++ b/lib/activeuuid/uuid.rb @@ -86,6 +86,7 @@ module UUID singleton_class.alias_method_chain :instantiate, :uuid before_create :generate_uuids_if_needed + after_initialize :generate_uuids_if_needed end module ClassMethods diff --git a/spec/lib/activerecord_spec.rb b/spec/lib/activerecord_spec.rb index 316d086..ed2ba65 100644 --- a/spec/lib/activerecord_spec.rb +++ b/spec/lib/activerecord_spec.rb @@ -96,6 +96,28 @@ let(:model) { described_class } subject { model } + context 'new record' do + let!(:article) { Fabricate.build :uuid_article } + subject { article } + let(:uuid) { UUIDTools::UUID.random_create } + let(:string) { uuid.to_s } + before { subject.another_uuid = string } + + context 'validation' do + its(:id) { should be_nil } + its(:another_uuid) { should be_a UUIDTools::UUID } + specify { subject.should be_new_record } + specify { subject.should be_valid } + end + + context 'save without validation' do + before { subject.save(validate: false) } + + its(:id) { should be_a UUIDTools::UUID } + specify { subject.should be_valid } + end + end + context 'model' do its(:primary_key) { should == 'id' } its(:all) { should == [article] } @@ -184,4 +206,4 @@ end end end -end \ No newline at end of file +end diff --git a/spec/support/models/uuid_article.rb b/spec/support/models/uuid_article.rb index 0292bb9..0894d0c 100644 --- a/spec/support/models/uuid_article.rb +++ b/spec/support/models/uuid_article.rb @@ -1,3 +1,7 @@ class UuidArticle < ActiveRecord::Base include ActiveUUID::UUID + + validates :id, presence: true, uniqueness: true, length: { in: 32..40 }, unless: :new_record? + validates :another_uuid, presence: true, uniqueness: true, length: { in: 32..40 }, unless: :new_record? + end