Skip to content

Commit

Permalink
Add hoc sequences in create_list
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammednasser-32 committed May 12, 2024
1 parent c0f2679 commit f5fbc18
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/factory_bot/strategy_syntax_method_registrar.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def define_list_strategy_method

Array.new(amount) do |i|
block_with_index = StrategySyntaxMethodRegistrar.with_index(block, i)
send(strategy_name, name, *traits_and_overrides, &block_with_index)
send(strategy_name, name, *evaluate_sequence_attributes(traits_and_overrides, i), &block_with_index)
end
end
end
Expand Down
12 changes: 12 additions & 0 deletions lib/factory_bot/syntax/methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,18 @@ def generate_list(name, count)
Internal.sequence_by_name(name).next
end
end

def build_sequence(&block)
block
end

def evaluate_sequence_attributes(traits_and_overrides, i)
traits_and_overrides.map do |attribute|
next attribute unless attribute.is_a?(Hash)

attribute.transform_values { |value| value.respond_to?(:call) ? value.call(i) : value }
end
end
end
end
end
10 changes: 10 additions & 0 deletions spec/acceptance/create_list_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@
end
end

context "with sequencial attributes" do
subject { FactoryBot.create_list(:post, 20, title: FactoryBot.build_sequence{|n| "title_#{n}"}) }

it "create sequencial attribute values" do
subject.each_with_index do |record, i|
expect(record.title).to eq "title_#{i}"
end
end
end

context "with a block" do
subject do
FactoryBot.create_list(:post, 20, title: "The Listing of the Block") do |post|
Expand Down

0 comments on commit f5fbc18

Please sign in to comment.