diff --git a/lib/seed-fu/active_record_extension.rb b/lib/seed-fu/active_record_extension.rb index 789cbc5..d19fcc3 100644 --- a/lib/seed-fu/active_record_extension.rb +++ b/lib/seed-fu/active_record_extension.rb @@ -32,6 +32,9 @@ def seed(*args, &block) SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block)).seed end + def seed!(*args, &block) + SeedFu::Seeder.new(self, *parse_seed_fu_args(args, block), validate_models: true).seed + end # Has the same syntax as {#seed}, but if a record already exists with the same values for # constraining attributes, it will not be updated. # diff --git a/lib/seed-fu/seeder.rb b/lib/seed-fu/seeder.rb index def2a43..10f6bc4 100644 --- a/lib/seed-fu/seeder.rb +++ b/lib/seed-fu/seeder.rb @@ -17,6 +17,8 @@ class Seeder # @option options [Boolean] :quiet (SeedFu.quiet) If true, output will be silenced # @option options [Boolean] :insert_only (false) If true then existing records which match the # constraints will not be updated, even if the seed data has changed + # @option options [Boolean] :validate_models (false) If true then seeded models will be validated + # when inserted/updated. def initialize(model_class, constraints, data, options = {}) @model_class = model_class @constraints = constraints.to_a.empty? ? [:id] : constraints @@ -71,7 +73,7 @@ def seed_record(data) else record.assign_attributes(data) end - record.save(:validate => false) || raise(ActiveRecord::RecordNotSaved, 'Record not saved!') + record.save(:validate => !!@options[:validate_models]) || raise(ActiveRecord::RecordNotSaved, 'Record not saved!') record end diff --git a/spec/seeder_spec.rb b/spec/seeder_spec.rb index 0b4e009..76e492a 100644 --- a/spec/seeder_spec.rb +++ b/spec/seeder_spec.rb @@ -172,4 +172,15 @@ it "should raise an ActiveRecord::RecordNotSaved exception if any records fail to save" do expect { SeededModel.seed(:fail_to_save => true, :title => "Foo") }.to raise_error(ActiveRecord::RecordNotSaved) end + + describe "seed!" do + it "should raise an ActiveRecord::RecordNotSaved exception if a record is invalid" do + expect { SeededModel.seed!(:title => nil) }.to raise_error(ActiveRecord::RecordNotSaved) + end + + it "should save a model when it is valid" do + result = SeededModel.seed!(:title => "Foo") + expect(result.all?(&:persisted?)).to be_truthy + end + end end