From eac7d5f949592683e062d6760376b387483a67e7 Mon Sep 17 00:00:00 2001 From: Gonzalo Rodriguez Date: Thu, 3 May 2012 00:20:41 -0300 Subject: [PATCH] Adds support for :all_or_none option on #import --- lib/activerecord-import/import.rb | 8 +++++-- test/import_test.rb | 40 ++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/lib/activerecord-import/import.rb b/lib/activerecord-import/import.rb index f32e64b..51e396d 100644 --- a/lib/activerecord-import/import.rb +++ b/lib/activerecord-import/import.rb @@ -254,8 +254,12 @@ class ActiveRecord::Base end end array_of_attributes.compact! - - num_inserts = array_of_attributes.empty? ? 0 : import_without_validations_or_callbacks( column_names, array_of_attributes, options ) + + num_inserts = if array_of_attributes.empty? || options[:all_or_none] && failed_instances.any? + 0 + else + import_without_validations_or_callbacks( column_names, array_of_attributes, options ) + end ActiveRecord::Import::Result.new(failed_instances, num_inserts) end diff --git a/test/import_test.rb b/test/import_test.rb index d89c5de..f96b972 100644 --- a/test/import_test.rb +++ b/test/import_test.rb @@ -65,7 +65,45 @@ describe "#import" do end end end - + + context "with :all_or_none option" do + let(:columns) { %w(title author_name) } + let(:valid_values) { [[ "LDAP", "Jerry Carter"], ["Rails Recipes", "Chad Fowler"]] } + let(:invalid_values) { [[ "The RSpec Book", ""], ["Agile+UX", ""]] } + let(:mixed_values) { valid_values + invalid_values } + + context "with validation checks turned on" do + it "should import valid data" do + assert_difference "Topic.count", +2 do + result = Topic.import columns, valid_values, :all_or_none => true + end + end + + it "should not import invalid data" do + assert_no_difference "Topic.count" do + result = Topic.import columns, invalid_values, :all_or_none => true + end + end + + it "should not import valid data when mixed with invalid data" do + assert_no_difference "Topic.count" do + result = Topic.import columns, mixed_values, :all_or_none => true + end + end + + it "should report the failed instances" do + results = Topic.import columns, mixed_values, :all_or_none => true + assert_equal invalid_values.size, results.failed_instances.size + results.failed_instances.each { |e| assert_kind_of Topic, e } + end + + it "should report the zero inserts" do + results = Topic.import columns, mixed_values, :all_or_none => true + assert_equal 0, results.num_inserts + end + end + end + context "with :synchronize option" do context "synchronizing on new records" do let(:new_topics) { Build(3, :topics) }