Add *_pair methods to create only two records

This introduces a set of methods for each build strategy where only two
records are created. Because the *_list methods can create an arbitrary
number (often too high), this introduces *_pair to ensure only two
records are created (and the number 2 doesn't need to be specified in
the call).
This commit is contained in:
Andy Waite and Josh Clayton 2013-10-25 15:50:58 -04:00 committed by Joshua Clayton
parent 7fd7121162
commit b9e1dde7e8
4 changed files with 56 additions and 0 deletions

View File

@ -868,6 +868,13 @@ To set the attributes for each of the factories, you can pass in a hash as you n
twenty_year_olds = FactoryGirl.build_list(:user, 25, date_of_birth: 20.years.ago)
```
There's also a set of `*_pair` methods for creating two records at a time:
```ruby
built_users = FactoryGirl.build_pair(:user) # array of two built users
created_users = FactoryGirl.create_pair(:user) # array of two created users
```
Custom Construction
-------------------

View File

@ -8,6 +8,7 @@ module FactoryGirl
def define_strategy_methods
define_singular_strategy_method
define_list_strategy_method
define_pair_strategy_method
end
private
@ -28,6 +29,14 @@ module FactoryGirl
end
end
def define_pair_strategy_method
strategy_name = @strategy_name
define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block|
2.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
end
end
def define_syntax_method(name, &block)
FactoryGirl::Syntax::Methods.module_exec do
define_method(name, &block)

View File

@ -0,0 +1,32 @@
require 'spec_helper'
describe "create multiple instances" do
before do
define_model('Post', title: :string, position: :integer)
FactoryGirl.define do
factory(:post) do |post|
post.title "Through the Looking Glass"
post.position { rand(10**4) }
end
end
end
context "without default attributes" do
subject { FactoryGirl.create_pair(:post) }
its(:length) { should eq 2 }
it "creates all the posts" do
subject.each do |record|
expect(record).not_to be_new_record
end
end
it "uses the default factory values" do
subject.each do |record|
expect(record.title).to eq "Through the Looking Glass"
end
end
end
end

View File

@ -49,6 +49,14 @@ describe "register custom strategies" do
expect(inserted_items.length).to eq 2
expect(inserted_items.map(&:name)).to eq ["Custom strategy", "Custom strategy"]
end
it "allows using the *_pair method to build a list using a custom strategy" do
FactoryGirl.register_strategy(:insert, custom_strategy)
inserted_items = FactoryGirl.insert_pair(:named_object)
expect(inserted_items.length).to eq 2
expect(inserted_items.map(&:name)).to eq ["Custom strategy", "Custom strategy"]
end
end
describe "including FactoryGirl::Syntax::Methods when custom strategies have been declared" do