Skip to content

Commit

Permalink
Add seed! method that validates models
Browse files Browse the repository at this point in the history
  • Loading branch information
bforma committed Jul 11, 2016
1 parent 9d393b2 commit 229ee88
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
3 changes: 3 additions & 0 deletions lib/seed-fu/active_record_extension.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand Down
4 changes: 3 additions & 1 deletion lib/seed-fu/seeder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions spec/seeder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 229ee88

Please sign in to comment.