Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add seed! method that validates models #97

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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