thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.91k stars 2.6k forks source link

Add feature: attribute scoped sequence #1640

Closed kakubin closed 3 months ago

kakubin commented 5 months ago

New feature useful in the following case

ActiveRecord::Schema.define do
  create_table :todo_lists do; end

  create_table :todo_items do |t|
    t.references :todo_list, null: false
    t.integer :priority, default: 1, null: false
    t.index [:todo_list_id, :priority], unique: true
  end
end

FactoryBot.define do
  factory :todo_item do
    scoped_sequence(:priority, :todo_list_id)
  end
end

attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>1}
attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>2} # generate attribute value `priority` sequentially
attributes_for(:todo_item, todo_list_id: 2) # => {:todo_list_id=>2, :priority=>1} # when value of scope attribute is different, another sequential number is generated.
attributes_for(:todo_item, todo_list_id: 1) # => {:todo_list_id=>1, :priority=>3}
kakubin commented 3 months ago

https://github.com/kakubin/factory_bot-scoped_sequence