mirror of
https://github.com/thoughtbot/factory_bot.git
synced 2022-11-09 11:43:51 -05:00
0b53d28b4c
When using one of the `*_list` methods, allow the block to receive array index for each object: ```ruby posts = build_list(:post, 10, title: 'Post number') do |post, i| post.title = "#{post.title} #{i + 1}" end posts.first.title # => "Post number 1" posts.last.title # => "Post number 10" ``` A block that only takes in the object still works as before, as does leaving off the block entirely. Co-authored-by: Mike Countis <mike.countis@gmail.com>
68 lines
1.7 KiB
Ruby
68 lines
1.7 KiB
Ruby
describe "build multiple instances" do
|
|
before do
|
|
define_model("Post", title: :string, position: :integer)
|
|
|
|
FactoryBot.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 { FactoryBot.build_list(:post, 20) }
|
|
|
|
its(:length) { should eq 20 }
|
|
|
|
it "builds (but doesn't save) all the posts" do
|
|
subject.each do |record|
|
|
expect(record).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
|
|
|
|
context "with default attributes" do
|
|
subject { FactoryBot.build_list(:post, 20, title: "The Hunting of the Snark") }
|
|
|
|
it "overrides the default values" do
|
|
subject.each do |record|
|
|
expect(record.title).to eq "The Hunting of the Snark"
|
|
end
|
|
end
|
|
end
|
|
|
|
context "with a block" do
|
|
subject do
|
|
FactoryBot.build_list(:post, 20, title: "The Listing of the Block") do |post|
|
|
post.position = post.id
|
|
end
|
|
end
|
|
|
|
it "correctly uses the set value" do
|
|
subject.each do |record|
|
|
expect(record.position).to eq record.id
|
|
end
|
|
end
|
|
end
|
|
|
|
context "with a block that receives both the object and an index" do
|
|
subject do
|
|
FactoryBot.build_list(:post, 20, title: "The Indexed Block") do |post, index|
|
|
post.position = index
|
|
end
|
|
end
|
|
|
|
it "correctly uses the set value" do
|
|
subject.each_with_index do |record, index|
|
|
expect(record.position).to eq index
|
|
end
|
|
end
|
|
end
|
|
end
|