Skip to content

Commit

Permalink
Merged pull request ryanb#19 from ordinaryzelig/master.
Browse files Browse the repository at this point in the history
Pass iterator to populate block to reduce duplicates
  • Loading branch information
ryanb committed Apr 25, 2011
2 parents 91c37ab + 97cbcdd commit 842a11e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/populator/factory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@ def populate(amount, options = {}, &block)
# :per_query limit option is reached.
def build_records(amount, per_query, &block)
amount.times do
record = Record.new(@model_class, last_id_in_database + @records.size + 1)
index = last_id_in_database + @records.size + 1
record = Record.new(@model_class, index)
@records << record
block.call(record) if block
block.call(record, index) if block
save_records if @records.size >= per_query
end
end
Expand Down
12 changes: 12 additions & 0 deletions spec/populator/factory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@
@factory.populate(5, :per_query => 2)
$queries_executed.grep(/^insert/i).should have(3).records
end

it 'should pass index to populator block to help eliminate duplicates' do
Product.delete_all
indexes = []
num_to_populate = 5
@factory.populate(num_to_populate) do |product, index|
product.name = "unique name #{index}"
end
product_names = Product.all.map(&:name)
expected_product_names = (1..num_to_populate).to_a.map { |index| "unique name #{index}" }
product_names.should == expected_product_names
end
end

it "should only use two queries when nesting factories (one for each class)" do
Expand Down

0 comments on commit 842a11e

Please sign in to comment.