repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attributes_for_destructuring.rb
spec/acceptance/attributes_for_destructuring.rb
describe "Ruby 3.0: attributes_for destructuring syntax" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string) FactoryBot.define do factory :user do sequence(:email) { "email_#{_1}@example.com" } name { "John Doe" } end end end it "supports being destructured" do # rubocop:disable Lint/Syntax attributes_for(:user) => {name:, **attributes} # rubocop:enable Lint/Syntax expect(name).to eq("John Doe") expect(attributes.keys).to eq([:email]) expect(attributes.fetch(:email)).to match(/email_\d+@example.com/) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb
spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb
describe "syntax methods within dynamic attributes" do before do define_model("Post", title: :string, user_id: :integer) do belongs_to :user def generate "generate result" end end define_model("User", email: :string) FactoryBot.define do sequence(:email_address) { |n| "person-#{n}@example.com" } factory :user do email { generate(:email_address) } end factory :post do title { generate } user { build(:user) } end end end it "can access syntax methods from dynamic attributes" do expect(FactoryBot.build(:user).email).to eq "person-1@example.com" expect(FactoryBot.attributes_for(:user)[:email]).to eq "person-2@example.com" end it "can access syntax methods from dynamic attributes" do expect(FactoryBot.build(:post).user).to be_instance_of(User) end it "can access methods already existing on the class" do expect(FactoryBot.build(:post).title).to eq "generate result" expect(FactoryBot.attributes_for(:post)[:title]).to be_nil end it "allows syntax methods to be used when the block has an arity of 1" do FactoryBot.define do factory :post_using_block_with_variable, parent: :post do user { |_| build(:user) } end end expect(FactoryBot.build(:post_using_block_with_variable).user).to be_instance_of(User) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/modify_factories_spec.rb
spec/acceptance/modify_factories_spec.rb
describe "modifying factories" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string, admin: :boolean, email: :string, login: :string) FactoryBot.define do sequence(:email) { |n| "user#{n}@example.com" } factory :user do email after(:create) do |user| user.login = user.name.upcase if user.name end factory :admin do admin { true } end end end end context "simple modification" do before do FactoryBot.modify do factory :user do name { "Great User" } end end end subject { create(:user) } its(:name) { should eq "Great User" } its(:login) { should eq "GREAT USER" } it "doesn't allow the factory to be subsequently defined" do expect { FactoryBot.define { factory :user } }.to raise_error(FactoryBot::DuplicateDefinitionError, "Factory already registered: user") end it "does allow the factory to be subsequently modified" do FactoryBot.modify do factory :user do name { "Overridden again!" } end end expect(create(:user).name).to eq "Overridden again!" end end context "adding callbacks" do before do FactoryBot.modify do factory :user do name { "Great User" } after(:create) do |user| user.name = user.name.downcase user.login = nil end end end end subject { create(:user) } its(:name) { should eq "great user" } its(:login) { should be_nil } end context "reusing traits" do before do FactoryBot.define do trait :rockstar do name { "Johnny Rockstar!!!" } end end FactoryBot.modify do factory :user do rockstar email { "#{name}@example.com" } end end end subject { create(:user) } its(:name) { should eq "Johnny Rockstar!!!" } its(:email) { should eq "Johnny Rockstar!!!@example.com" } its(:login) { should eq "JOHNNY ROCKSTAR!!!" } end context "redefining attributes" do before do FactoryBot.modify do factory :user do email { "#{name}-modified@example.com" } name { "Great User" } end end end context "creating user" do context "without overrides" do subject { create(:user) } its(:name) { should eq "Great User" } its(:email) { should eq "Great User-modified@example.com" } end context "overriding the email" do subject { create(:user, email: "perfect@example.com") } its(:name) { should eq "Great User" } its(:email) { should eq "perfect@example.com" } end context "overriding the name" do subject { create(:user, name: "wonderful") } its(:name) { should eq "wonderful" } its(:email) { should eq "wonderful-modified@example.com" } end end context "creating admin" do context "without overrides" do subject { create(:admin) } its(:name) { should eq "Great User" } its(:email) { should eq "Great User-modified@example.com" } its(:admin) { should be true } end context "overriding the email" do subject { create(:admin, email: "perfect@example.com") } its(:name) { should eq "Great User" } its(:email) { should eq "perfect@example.com" } its(:admin) { should be true } end context "overriding the name" do subject { create(:admin, name: "wonderful") } its(:name) { should eq "wonderful" } its(:email) { should eq "wonderful-modified@example.com" } its(:admin) { should be true } end end end it "doesn't overwrite already defined child's attributes" do FactoryBot.modify do factory :user do admin { false } end end expect(create(:admin)).to be_admin end it "allows for overriding child classes" do FactoryBot.modify do factory :admin do admin { false } end end expect(create(:admin)).not_to be_admin end it "raises an exception if the factory was not defined before" do modify_unknown_factory = -> do FactoryBot.modify do factory :unknown_factory end end expect(&modify_unknown_factory).to raise_error(KeyError) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/activesupport_instrumentation_spec.rb
spec/acceptance/activesupport_instrumentation_spec.rb
unless ActiveSupport::Notifications.respond_to?(:subscribed) module SubscribedBehavior def subscribed(callback, *args) subscriber = subscribe(*args, &callback) yield ensure unsubscribe(subscriber) end end ActiveSupport::Notifications.extend SubscribedBehavior end describe "using ActiveSupport::Instrumentation to track run_factory interaction" do let(:slow_user_factory) { FactoryBot::Internal.factory_by_name("slow_user") } let(:user_factory) { FactoryBot::Internal.factory_by_name("user") } before do define_model("User", email: :string) define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user do email { "john@example.com" } factory :slow_user do after(:build) { Kernel.sleep(0.1) } end end factory :post do trait :with_user do user end end end end it "tracks proper time of creating the record" do time_to_execute = 0 callback = ->(_name, start, finish, _id, _payload) { time_to_execute = finish - start } ActiveSupport::Notifications.subscribed(callback, "factory_bot.run_factory") do FactoryBot.build(:slow_user) end expect(time_to_execute).to be >= 0.1 end it "builds the correct payload", :slow do tracked_invocations = {} callback = ->(_name, _start, _finish, _id, payload) do factory_name = payload[:name] strategy_name = payload[:strategy] factory = payload[:factory] tracked_invocations[factory_name] ||= {} tracked_invocations[factory_name][strategy_name] ||= 0 tracked_invocations[factory_name][strategy_name] += 1 tracked_invocations[factory_name][:factory] = factory end ActiveSupport::Notifications.subscribed(callback, "factory_bot.run_factory") do FactoryBot.build_list(:slow_user, 2) FactoryBot.build_list(:user, 5) FactoryBot.create_list(:user, 2) FactoryBot.attributes_for(:slow_user) user = FactoryBot.create(:user) FactoryBot.create(:post, user: user) FactoryBot.create_list(:post, 2, :with_user) end expect(tracked_invocations[:slow_user][:build]).to eq(2) expect(tracked_invocations[:slow_user][:attributes_for]).to eq(1) expect(tracked_invocations[:slow_user][:factory]).to eq(slow_user_factory) expect(tracked_invocations[:user][:build]).to eq(5) expect(tracked_invocations[:user][:factory]).to eq(user_factory) expect(tracked_invocations[:user][:create]).to eq(5) end end describe "using ActiveSupport::Instrumentation to track compile_factory interaction" do before do define_model("User", name: :string, email: :string) FactoryBot.define do factory :user do sequence(:email) { |n| "user_#{n}@example.com" } name { "User" } trait :special do name { "Special User" } end end end end it "tracks proper time of compiling the factory" do time_to_execute = {user: 0} callback = ->(_name, start, finish, _id, payload) { time_to_execute[payload[:name]] = (finish - start) } ActiveSupport::Notifications.subscribed(callback, "factory_bot.compile_factory") do FactoryBot.build(:user) end expect(time_to_execute[:user]).to be > 0 end it "builds the correct payload" do tracked_payloads = [] callback = ->(_name, _start, _finish, _id, payload) { tracked_payloads << payload } ActiveSupport::Notifications.subscribed(callback, "factory_bot.compile_factory") do FactoryBot.build(:user, :special) end factory_payload = tracked_payloads.detect { |payload| payload[:name] == :user } expect(factory_payload[:class]).to eq(User) expect(factory_payload[:attributes].map(&:name)).to eq([:email, :name]) expect(factory_payload[:traits].map(&:name)).to eq(["special"]) trait_payload = tracked_payloads.detect { |payload| payload[:name] == "special" } expect(trait_payload[:class]).to eq(User) expect(trait_payload[:attributes].map(&:name)).to eq([:name]) expect(trait_payload[:traits].map(&:name)).to eq(["special"]) end context "when factory with base traits" do before do define_model("Company", name: :string, email: :string) FactoryBot.define do trait :email do email { "#{name}@example.com" } end factory :company, traits: [:email] do name { "Charlie" } end end end it "builds the correct payload" do tracked_payloads = [] callback = ->(_name, _start, _finish, _id, payload) { tracked_payloads << payload } ActiveSupport::Notifications.subscribed(callback, "factory_bot.compile_factory") do FactoryBot.build(:company) end factory_payload = tracked_payloads.detect { |payload| payload[:name] == :company } expect(factory_payload[:class]).to eq(Company) expect(factory_payload[:attributes].map(&:name)).to eq([:name]) expect(factory_payload[:traits].map(&:name)).to eq([]) trait_payload = tracked_payloads.detect { |payload| payload[:name] == "email" } expect(trait_payload[:class]).to eq(Company) expect(trait_payload[:attributes].map(&:name)).to eq([:email]) expect(trait_payload[:traits].map(&:name)).to eq([]) end end context "when factory with additional traits" do before do define_model("Company", name: :string, email: :string) FactoryBot.define do trait :email do email { "#{name}@example.com" } end factory :company do name { "Charlie" } end end end it "builds the correct payload" do tracked_payloads = [] callback = ->(_name, _start, _finish, _id, payload) { tracked_payloads << payload } ActiveSupport::Notifications.subscribed(callback, "factory_bot.compile_factory") do FactoryBot.build(:company, :email) end factory_payload = tracked_payloads.detect { |payload| payload[:name] == :company } expect(factory_payload[:class]).to eq(Company) expect(factory_payload[:attributes].map(&:name)).to eq([:name]) expect(factory_payload[:traits].map(&:name)).to eq([]) trait_payload = tracked_payloads.detect { |payload| payload[:name] == "email" } expect(trait_payload[:class]).to eq(Company) expect(trait_payload[:attributes].map(&:name)).to eq([:email]) expect(trait_payload[:traits].map(&:name)).to eq([]) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/sequence_context_spec.rb
spec/acceptance/sequence_context_spec.rb
describe "sequences are evaluated in the correct context, directly & implicitly" do include FactoryBot::Syntax::Methods before do define_class("User") do attr_accessor :id, :name def awesome "aw yeah" end end end it "builds a sequence calling sprintf correctly" do FactoryBot.define do factory :sequence_with_sprintf, class: User do sequence(:id) { |n| sprintf("foo%d", n) } end end expect(FactoryBot.build(:sequence_with_sprintf).id).to eq "foo1" expect(build(:sequence_with_sprintf).id).to eq "foo2" end it "invokes the correct method on the instance" do FactoryBot.define do factory :sequence_with_public_method, class: User do sequence(:id) { public_method(:awesome).call } end end expect(FactoryBot.build(:sequence_with_public_method).id).to eq "aw yeah" expect(build(:sequence_with_public_method).id).to eq "aw yeah" end it "invokes a method with no arguments on the instance" do FactoryBot.define do factory :sequence_with_frozen, class: User do sequence(:id) { frozen? } end end expect(FactoryBot.build(:sequence_with_frozen).id).to be false expect(build(:sequence_with_frozen).id).to be false end it "allows direct reference of a method in a sequence" do FactoryBot.define do factory :sequence_referencing_attribute_directly, class: User do sequence(:id) { |n| "#{awesome}#{n}" } end end expect(FactoryBot.build(:sequence_referencing_attribute_directly).id).to eq "aw yeah1" expect(build(:sequence_referencing_attribute_directly).id).to eq "aw yeah2" end context "with inherited factories" do it "uses the parent's sequenced attribute" do FactoryBot.define do factory :parent, class: User do sequence(:id) { |n| "id_#{n}" } factory :child, class: User end end parents = FactoryBot.build_list(:parent, 3) expect(parents[0].id).to eq "id_1" expect(parents[1].id).to eq "id_2" expect(parents[2].id).to eq "id_3" children = build_list(:child, 3) expect(children[0].id).to eq "id_4" expect(children[1].id).to eq "id_5" expect(children[2].id).to eq "id_6" end it "invokes the parent's sequenced trait from within a child's inherited trait" do FactoryBot.define do sequence :global_seq factory :parent, class: User do trait :with_sequenced_id do sequence(:id) { |n| "id_#{n}" } end factory :child, class: User end end parent_ids = FactoryBot.build_list(:parent, 3, :with_sequenced_id).map(&:id) expect(parent_ids).to eq ["id_1", "id_2", "id_3"] child_ids = build_list(:child, 3, :with_sequenced_id).map(&:id) expect(child_ids).to eq ["id_4", "id_5", "id_6"] end it "invokes the child's sequenced trait from within the child's own trait" do FactoryBot.define do sequence :global_sequence factory :parent, class: User do trait :with_sequenced_id do sequence(:id) { |n| "id_#{n}" } end factory :child, class: User, aliases: [:toddler, :teen] do sequence(:id) { |n| "id_#{n}" } trait :with_own_sequence do sequence(:id, 1000, aliases: [:woo_hoo, :woo_hoo_2]) { |n| "id_#{n}" } end end end end parents = FactoryBot.build_list(:parent, 3, :with_sequenced_id) expect(parents[0].id).to eq "id_1" expect(parents[1].id).to eq "id_2" expect(parents[2].id).to eq "id_3" children = build_list(:child, 3) expect(children[0].id).to eq "id_1" expect(children[1].id).to eq "id_2" expect(children[2].id).to eq "id_3" children = FactoryBot.build_list(:child, 3, :with_sequenced_id, :with_own_sequence) expect(children[0].id).to eq "id_1000" expect(children[1].id).to eq "id_1001" expect(children[2].id).to eq "id_1002" end it "redefines a child's sequence" do FactoryBot.define do factory :parent, class: User do sequence(:id) { |n| "parent_#{n}" } factory :child, class: User do sequence(:id) { |n| "child_#{n}" } end end end parents = FactoryBot.build_list(:parent, 3) expect(parents[0].id).to eq "parent_1" expect(parents[1].id).to eq "parent_2" expect(parents[2].id).to eq "parent_3" children = build_list(:child, 3) expect(children[0].id).to eq "child_1" expect(children[1].id).to eq "child_2" expect(children[2].id).to eq "child_3" end it "maintains context separation" do FactoryBot.define do sequence(:id) { |n| "global_#{n}" } factory :parent, class: User do sequence(:id) { |n| "parent_#{n}" } factory :child, class: User do sequence(:id) { |n| "child_#{n}" } end end factory :sibling, class: User do sequence(:id) { |n| "sibling_#{n}" } end end globals = FactoryBot.generate_list(:id, 3) expect(globals[0]).to eq "global_1" expect(globals[1]).to eq "global_2" expect(globals[2]).to eq "global_3" parents = build_list(:parent, 3) expect(parents[0].id).to eq "parent_1" expect(parents[1].id).to eq "parent_2" expect(parents[2].id).to eq "parent_3" children = FactoryBot.build_list(:child, 3) expect(children[0].id).to eq "child_1" expect(children[1].id).to eq "child_2" expect(children[2].id).to eq "child_3" siblings = build_list(:sibling, 3) expect(siblings[0].id).to eq "sibling_1" expect(siblings[1].id).to eq "sibling_2" expect(siblings[2].id).to eq "sibling_3" end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/transient_attributes_spec.rb
spec/acceptance/transient_attributes_spec.rb
describe "transient attributes" do before do define_model("User", name: :string, email: :string) FactoryBot.define do sequence(:name) { |n| "John #{n}" } factory :user do transient do four { 2 + 2 } rockstar { true } upcased { false } end name { "#{FactoryBot.generate(:name)}#{" - Rockstar" if rockstar}" } email { "#{name.downcase}#{four}@example.com" } after(:create) do |user, evaluator| user.name.upcase! if evaluator.upcased end end end end context "returning attributes for a factory" do subject { FactoryBot.attributes_for(:user, rockstar: true) } it { should_not have_key(:four) } it { should_not have_key(:rockstar) } it { should_not have_key(:upcased) } it { should have_key(:name) } it { should have_key(:email) } end context "with a transient variable assigned" do let(:rockstar) { FactoryBot.create(:user, rockstar: true, four: "1234") } let(:rockstar_with_name) { FactoryBot.create(:user, name: "Jane Doe", rockstar: true) } let(:upcased_rockstar) { FactoryBot.create(:user, rockstar: true, upcased: true) } let(:groupie) { FactoryBot.create(:user, rockstar: false) } it "generates the correct attributes on a rockstar" do expect(rockstar.name).to eq "John 1 - Rockstar" expect(rockstar.email).to eq "john 1 - rockstar1234@example.com" end it "generates the correct attributes on an upcased rockstar" do expect(upcased_rockstar.name).to eq "JOHN 1 - ROCKSTAR" expect(upcased_rockstar.email).to eq "john 1 - rockstar4@example.com" end it "generates the correct attributes on a groupie" do expect(groupie.name).to eq "John 1" expect(groupie.email).to eq "john 14@example.com" end it "generates the correct attributes on a rockstar with a name" do expect(rockstar_with_name.name).to eq "Jane Doe" expect(rockstar_with_name.email).to eq "jane doe4@example.com" end end context "without transient variables assigned" do let(:rockstar) { FactoryBot.create(:user) } it "uses the default value of the attribute" do expect(rockstar.name).to eq "John 1 - Rockstar" end end end describe "transient sequences" do before do define_model("User", name: :string) FactoryBot.define do factory :user do transient do sequence(:counter) end name { "John Doe #{counter}" } end end end it "increments sequences correctly" do expect(FactoryBot.build(:user).name).to eq "John Doe 1" expect(FactoryBot.build(:user).name).to eq "John Doe 2" end end describe "assigning values from a transient attribute" do before do define_class("User") do attr_accessor :foo_id, :foo_name end define_class("Foo") do attr_accessor :id, :name def initialize(id, name) @id = id @name = name end end FactoryBot.define do factory :user do transient do foo { Foo.new("id-of-foo", "name-of-foo") } end foo_id { foo.id } foo_name { foo.name } end end end it "does not ignore an _id attribute that is an alias for a transient attribute" do user = FactoryBot.build(:user, foo: Foo.new("passed-in-id-of-foo", "passed-in-name-of-foo")) expect(user.foo_id).to eq "passed-in-id-of-foo" expect(user.foo_name).to eq "passed-in-name-of-foo" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/create_spec.rb
spec/acceptance/create_spec.rb
describe "a created instance" do include FactoryBot::Syntax::Methods before do define_model("User") define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user factory :post do user end end end subject { create("post") } it { should_not be_new_record } it "assigns and saves associations" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "a created instance, specifying strategy: :build" do include FactoryBot::Syntax::Methods before do define_model("User") define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user factory :post do association(:user, strategy: :build) end end end subject { create(:post) } it "saves associations (strategy: :build only affects build, not create)" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "a custom create" do include FactoryBot::Syntax::Methods before do define_class("User") do def initialize @persisted = false end def persist @persisted = true end def persisted? @persisted end end FactoryBot.define do factory :user do to_create(&:persist) end end end it "uses the custom create block instead of save" do expect(FactoryBot.create(:user)).to be_persisted end end describe "a custom create passing in an evaluator" do before do define_class("User") do attr_accessor :name end FactoryBot.define do factory :user do transient { creation_name { "evaluator" } } to_create do |user, evaluator| user.name = evaluator.creation_name end end end end it "passes the evaluator to the custom create block" do expect(FactoryBot.create(:user).name).to eq "evaluator" end end describe "calling `create` with a block" do include FactoryBot::Syntax::Methods before do define_model("Company", name: :string) FactoryBot.define do factory :company end end it "passes the created instance" do create(:company, name: "thoughtbot") do |company| expect(company.name).to eq("thoughtbot") end end it "returns the created instance" do expected = nil result = create(:company) { |company| expected = company "hello!" } expect(result).to eq expected end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/traits_spec.rb
spec/acceptance/traits_spec.rb
describe "an instance generated by a factory with multiple traits" do before do define_model("User", name: :string, admin: :boolean, gender: :string, email: :string, date_of_birth: :date, great: :string) FactoryBot.define do factory :user do name { "John" } trait :great do great { "GREAT!!!" } end trait :great do great { "EVEN GREATER!!!" } end trait :admin do admin { true } end trait :admin_trait do admin { true } end trait :male do name { "Joe" } gender { "Male" } end trait :female do name { "Jane" } gender { "Female" } end trait :make_it_great do great end factory :great_user do great end factory :even_greater_user do great trait :great do great { "EVEN GREATER!!!" } end end factory :greatest_user do trait :great do great { "GREATEST EVER!!!" } end end factory :admin, traits: [:admin] factory :male_user do male factory :child_male_user do date_of_birth { Date.parse("1/1/2000") } end end factory :female, traits: [:female] do trait :admin do admin { true } name { "Judy" } end factory :female_great_user do great end factory :female_admin_judy, traits: [:admin] end factory :female_admin, traits: [:female, :admin] factory :female_after_male_admin, traits: [:male, :female, :admin] factory :male_after_female_admin, traits: [:female, :male, :admin] end trait :email do email { "#{name}@example.com" } end factory :user_with_email, class: User, traits: [:email] do name { "Bill" } end end end context "the parent class" do subject { FactoryBot.create(:user) } its(:name) { should eq "John" } its(:gender) { should be_nil } it { should_not be_admin } end context "the child class with one trait" do subject { FactoryBot.create(:admin) } its(:name) { should eq "John" } its(:gender) { should be_nil } it { should be_admin } end context "the other child class with one trait" do subject { FactoryBot.create(:female) } its(:name) { should eq "Jane" } its(:gender) { should eq "Female" } it { should_not be_admin } end context "the child with multiple traits" do subject { FactoryBot.create(:female_admin) } its(:name) { should eq "Jane" } its(:gender) { should eq "Female" } it { should be_admin } end context "the child with multiple traits and overridden attributes" do subject { FactoryBot.create(:female_admin, name: "Jill", gender: nil) } its(:name) { should eq "Jill" } its(:gender) { should be_nil } it { should be_admin } end context "the child with multiple traits who override the same attribute" do context "when the male assigns name after female" do subject { FactoryBot.create(:male_after_female_admin) } its(:name) { should eq "Joe" } its(:gender) { should eq "Male" } it { should be_admin } end context "when the female assigns name after male" do subject { FactoryBot.create(:female_after_male_admin) } its(:name) { should eq "Jane" } its(:gender) { should eq "Female" } it { should be_admin } end end context "child class with scoped trait and inherited trait" do subject { FactoryBot.create(:female_admin_judy) } its(:name) { should eq "Judy" } its(:gender) { should eq "Female" } it { should be_admin } end context "factory using global trait" do subject { FactoryBot.create(:user_with_email) } its(:name) { should eq "Bill" } its(:email) { should eq "Bill@example.com" } end context "factory created with alternate syntax for specifying trait" do subject { FactoryBot.create(:male_user) } its(:gender) { should eq "Male" } context "where trait name and attribute are the same" do subject { FactoryBot.create(:great_user) } its(:great) { should eq "GREAT!!!" } end context "where trait name and attribute are the same and attribute is overridden" do subject { FactoryBot.create(:great_user, great: "SORT OF!!!") } its(:great) { should eq "SORT OF!!!" } end end context "factory with trait defined multiple times" do subject { FactoryBot.create(:great_user) } its(:great) { should eq "GREAT!!!" } context "child factory redefining trait" do subject { FactoryBot.create(:even_greater_user) } its(:great) { should eq "EVEN GREATER!!!" } end end context "factory with implicit traits called by child" do it "calls the correct trait when parent built first" do user = FactoryBot.create(:user, :make_it_great) expect(user.great).to eq "GREAT!!!" end it "calls the correct trait when child built first" do greatest = FactoryBot.create(:greatest_user, :make_it_great) user = FactoryBot.create(:user, :make_it_great) expect(user.great).to eq "GREAT!!!" expect(greatest.great).to eq "GREATEST EVER!!!" end end context "child factory created where trait attributes are inherited" do subject { FactoryBot.create(:child_male_user) } its(:gender) { should eq "Male" } its(:date_of_birth) { should eq Date.parse("1/1/2000") } end context "child factory using grandparents' trait" do subject { FactoryBot.create(:female_great_user) } its(:great) { should eq "GREAT!!!" } end end describe "trait indifferent access" do context "when trait is defined as a string" do it "can be invoked with a string" do build_user_factory_with_admin_trait("admin") user = FactoryBot.build(:user, "admin") expect(user).to be_admin end it "can be invoked with a symbol" do build_user_factory_with_admin_trait("admin") user = FactoryBot.build(:user, :admin) expect(user).to be_admin end end context "when trait is defined as a symbol" do it "can be invoked with a string" do build_user_factory_with_admin_trait(:admin) user = FactoryBot.build(:user, "admin") expect(user).to be_admin end it "can be invoked with a symbol" do build_user_factory_with_admin_trait(:admin) user = FactoryBot.build(:user, :admin) expect(user).to be_admin end end context "when trait is defined as integer" do it "can be invoked with a string" do build_user_factory_with_admin_trait(42) user = FactoryBot.build(:user, "42") expect(user).to be_admin end it "can be invoked with as integer" do build_user_factory_with_admin_trait(42) user = FactoryBot.build(:user, 42) expect(user).to be_admin end end context "when trait is defined as struct" do it "can be invoked with a string" do instance = Struct.new(:a, :b).new(1, "x") build_user_factory_with_admin_trait(instance) user = FactoryBot.build(:user, '#<struct a=1, b="x">') expect(user).to be_admin end it "can be invoked with a struct" do instance = Struct.new(:a, :b).new(1, "x") build_user_factory_with_admin_trait(instance) user = FactoryBot.build(:user, instance) expect(user).to be_admin end end def build_user_factory_with_admin_trait(trait_name) define_model("User", admin: :boolean) FactoryBot.define do factory :user do admin { false } trait trait_name do admin { true } end end end end end describe "looking up traits that don't exist" do context "when passing an invalid override trait" do it "raises a KeyError" do define_class("User") FactoryBot.define do factory :user end expect { FactoryBot.build(:user, double("not a trait")) } .to raise_error(KeyError) end end context "when the factory includes an invalid default trait" do it "raises a KeyError including the factory name" do define_class("User") FactoryBot.define do factory :user do inaccessible_trait end factory :some_other_factory do trait :inaccessible_trait end end expect { FactoryBot.build(:user) }.to raise_error( KeyError, 'Trait not registered: "inaccessible_trait" referenced within "user" definition' ) end it "maintains 'Did you mean?' suggestions at the end of the error message" do define_class("User") FactoryBot.define do trait :not_quit factory :user do not_quite end end expect { FactoryBot.build(:user) }.to raise_did_you_mean_error end end context "when a trait includes an invalid default trait" do it "raises a KeyError including the factory name" do define_class("User") FactoryBot.define do factory :user do trait :admin do inaccessible_trait end end factory :some_other_factory do trait :inaccessible_trait end end expect { FactoryBot.build(:user, :admin) }.to raise_error( KeyError, 'Trait not registered: "inaccessible_trait" referenced within "admin" definition' ) end end end describe "traits with callbacks" do before do define_model("User", name: :string) FactoryBot.define do factory :user do name { "John" } trait :great do after(:create) { |user| user.name.upcase! } end trait :awesome do after(:create) { |user| user.name = "awesome" } end factory :caps_user, traits: [:great] factory :awesome_user, traits: [:great, :awesome] factory :caps_user_implicit_trait do great end end end end context "when the factory has a trait passed via arguments" do subject { FactoryBot.create(:caps_user) } its(:name) { should eq "JOHN" } end context "when the factory has an implicit trait" do subject { FactoryBot.create(:caps_user_implicit_trait) } its(:name) { should eq "JOHN" } end it "executes callbacks in the order assigned" do expect(FactoryBot.create(:awesome_user).name).to eq "awesome" end end describe "traits added via strategy" do before do define_model("User", name: :string, admin: :boolean) FactoryBot.define do factory :user do name { "John" } trait :admin do admin { true } end trait :great do after(:create) { |user| user.name.upcase! } end end end end context "adding traits in create" do subject { FactoryBot.create(:user, :admin, :great, name: "Joe") } its(:admin) { should be true } its(:name) { should eq "JOE" } it "doesn't modify the user factory" do subject expect(FactoryBot.create(:user)).not_to be_admin expect(FactoryBot.create(:user).name).to eq "John" end end context "adding traits in build" do subject { FactoryBot.build(:user, :admin, :great, name: "Joe") } its(:admin) { should be true } its(:name) { should eq "Joe" } end context "adding traits in attributes_for" do subject { FactoryBot.attributes_for(:user, :admin, :great) } its([:admin]) { should be true } its([:name]) { should eq "John" } end context "adding traits in build_stubbed" do subject { FactoryBot.build_stubbed(:user, :admin, :great, name: "Jack") } its(:admin) { should be true } its(:name) { should eq "Jack" } end context "adding traits in create_list" do subject { FactoryBot.create_list(:user, 2, :admin, :great, name: "Joe") } its(:length) { should eq 2 } it "creates all the records" do subject.each do |record| expect(record.admin).to be true expect(record.name).to eq "JOE" end end end context "adding traits in build_list" do subject { FactoryBot.build_list(:user, 2, :admin, :great, name: "Joe") } its(:length) { should eq 2 } it "builds all the records" do subject.each do |record| expect(record.admin).to be true expect(record.name).to eq "Joe" end end end end describe "traits and dynamic attributes that are applied simultaneously" do before do define_model("User", name: :string, email: :string, combined: :string) FactoryBot.define do trait :email do email { "#{name}@example.com" } end factory :user do name { "John" } email combined { "#{name} <#{email}>" } end end end subject { FactoryBot.build(:user) } its(:name) { should eq "John" } its(:email) { should eq "John@example.com" } its(:combined) { should eq "John <John@example.com>" } end describe "applying inline traits" do before do define_model("User") do has_many :posts end define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user do trait :with_post do posts { [Post.new] } end end end end it "applies traits only to the instance generated for that call" do expect(FactoryBot.create(:user, :with_post).posts).not_to be_empty expect(FactoryBot.create(:user).posts).to be_empty expect(FactoryBot.create(:user, :with_post).posts).not_to be_empty end end describe "inline traits overriding existing attributes" do before do define_model("User", status: :string) FactoryBot.define do factory :user do status { "pending" } trait(:accepted) { status { "accepted" } } trait(:declined) { status { "declined" } } factory :declined_user, traits: [:declined] factory :extended_declined_user, traits: [:declined] do status { "extended_declined" } end end end end it "returns the default status" do expect(FactoryBot.build(:user).status).to eq "pending" end it "prefers inline trait attributes over default attributes" do expect(FactoryBot.build(:user, :accepted).status).to eq "accepted" end it "prefers traits on a factory over default attributes" do expect(FactoryBot.build(:declined_user).status).to eq "declined" end it "prefers inline trait attributes over traits on a factory" do expect(FactoryBot.build(:declined_user, :accepted).status).to eq "accepted" end it "prefers attributes on factories over attributes from non-inline traits" do expect(FactoryBot.build(:extended_declined_user).status).to eq "extended_declined" end it "prefers inline traits over attributes on factories" do expect(FactoryBot.build(:extended_declined_user, :accepted).status).to eq "accepted" end it "prefers overridden attributes over attributes from traits, inline traits, or attributes on factories" do user = FactoryBot.build(:extended_declined_user, :accepted, status: "completely overridden") expect(user.status).to eq "completely overridden" end end describe "making sure the factory is properly compiled the first time we want to instantiate it" do before do define_model("User", role: :string, gender: :string, age: :integer) FactoryBot.define do factory :user do trait(:female) { gender { "female" } } trait(:admin) { role { "admin" } } factory :female_user do female end end end end it "can honor traits on the very first call" do user = FactoryBot.build(:female_user, :admin, age: 30) expect(user.gender).to eq "female" expect(user.age).to eq 30 expect(user.role).to eq "admin" end end describe "traits with to_create" do before do define_model("User", name: :string) FactoryBot.define do factory :user do trait :with_to_create do to_create { |instance| instance.name = "to_create" } end factory :sub_user do to_create { |instance| instance.name = "sub" } factory :child_user end factory :sub_user_with_trait do with_to_create factory :child_user_with_trait end factory :sub_user_with_trait_and_override do with_to_create to_create { |instance| instance.name = "sub with trait and override" } factory :child_user_with_trait_and_override end end end end it "can apply to_create from traits" do expect(FactoryBot.create(:user, :with_to_create).name).to eq "to_create" end it "can apply to_create from the definition" do expect(FactoryBot.create(:sub_user).name).to eq "sub" expect(FactoryBot.create(:child_user).name).to eq "sub" end it "gives additional traits higher priority than to_create from the definition" do expect(FactoryBot.create(:sub_user, :with_to_create).name).to eq "to_create" expect(FactoryBot.create(:child_user, :with_to_create).name).to eq "to_create" end it "gives base traits normal priority" do expect(FactoryBot.create(:sub_user_with_trait).name).to eq "to_create" expect(FactoryBot.create(:child_user_with_trait).name).to eq "to_create" end it "gives base traits lower priority than overrides" do expect(FactoryBot.create(:sub_user_with_trait_and_override).name).to eq "sub with trait and override" expect(FactoryBot.create(:child_user_with_trait_and_override).name).to eq "sub with trait and override" end it "gives additional traits higher priority than base traits and factory definition" do FactoryBot.define do trait :overridden do to_create { |instance| instance.name = "completely overridden" } end end sub_user = FactoryBot.create(:sub_user_with_trait_and_override, :overridden) child_user = FactoryBot.create(:child_user_with_trait_and_override, :overridden) expect(sub_user.name).to eq "completely overridden" expect(child_user.name).to eq "completely overridden" end end describe "traits with initialize_with" do before do define_class("User") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :user do trait :with_initialize_with do initialize_with { new("initialize_with") } end factory :sub_user do initialize_with { new("sub") } factory :child_user end factory :sub_user_with_trait do with_initialize_with factory :child_user_with_trait end factory :sub_user_with_trait_and_override do with_initialize_with initialize_with { new("sub with trait and override") } factory :child_user_with_trait_and_override end end end end it "can apply initialize_with from traits" do expect(FactoryBot.build(:user, :with_initialize_with).name).to eq "initialize_with" end it "can apply initialize_with from the definition" do expect(FactoryBot.build(:sub_user).name).to eq "sub" expect(FactoryBot.build(:child_user).name).to eq "sub" end it "gives additional traits higher priority than initialize_with from the definition" do expect(FactoryBot.build(:sub_user, :with_initialize_with).name).to eq "initialize_with" expect(FactoryBot.build(:child_user, :with_initialize_with).name).to eq "initialize_with" end it "gives base traits normal priority" do expect(FactoryBot.build(:sub_user_with_trait).name).to eq "initialize_with" expect(FactoryBot.build(:child_user_with_trait).name).to eq "initialize_with" end it "gives base traits lower priority than overrides" do expect(FactoryBot.build(:sub_user_with_trait_and_override).name).to eq "sub with trait and override" expect(FactoryBot.build(:child_user_with_trait_and_override).name).to eq "sub with trait and override" end it "gives additional traits higher priority than base traits and factory definition" do FactoryBot.define do trait :overridden do initialize_with { new("completely overridden") } end end sub_user = FactoryBot.build(:sub_user_with_trait_and_override, :overridden) child_user = FactoryBot.build(:child_user_with_trait_and_override, :overridden) expect(sub_user.name).to eq "completely overridden" expect(child_user.name).to eq "completely overridden" end end describe "nested implicit traits" do before do define_class("User") do attr_accessor :gender, :role attr_reader :name def initialize(name) @name = name end end end shared_examples_for "assigning data from traits" do it "assigns the correct values" do user = FactoryBot.create(:user, :female_admin) expect(user.gender).to eq "FEMALE" expect(user.role).to eq "ADMIN" expect(user.name).to eq "Jane Doe" end end context "defined outside the factory" do before do FactoryBot.define do trait :female do gender { "female" } to_create { |instance| instance.gender = instance.gender.upcase } end trait :jane_doe do initialize_with { new("Jane Doe") } end trait :admin do role { "admin" } after(:build) { |instance| instance.role = instance.role.upcase } end trait :female_admin do female admin jane_doe end factory :user end end it_should_behave_like "assigning data from traits" end context "defined inside the factory" do before do FactoryBot.define do factory :user do trait :female do gender { "female" } to_create { |instance| instance.gender = instance.gender.upcase } end trait :jane_doe do initialize_with { new("Jane Doe") } end trait :admin do role { "admin" } after(:build) { |instance| instance.role = instance.role.upcase } end trait :female_admin do female admin jane_doe end end end end it_should_behave_like "assigning data from traits" end end describe "implicit traits containing callbacks" do before do define_model("User", value: :integer) FactoryBot.define do factory :user do value { 0 } trait :trait_with_callback do after(:build) { |user| user.value += 1 } end factory :user_with_trait_with_callback do trait_with_callback end end end end it "only runs the callback once" do expect(FactoryBot.build(:user_with_trait_with_callback).value).to eq 1 end end describe "traits used in associations" do before do define_model("User", admin: :boolean, name: :string) define_model("Comment", user_id: :integer) do belongs_to :user end define_model("Order", creator_id: :integer) do belongs_to :creator, class_name: "User" end define_model("Post", author_id: :integer) do belongs_to :author, class_name: "User" end FactoryBot.define do factory :user do admin { false } trait :admin do admin { true } end end factory :post do association :author, factory: [:user, :admin], name: "John Doe" end factory :comment do association :user, :admin, name: "Joe Slick" end factory :order do association :creator, :admin, factory: :user, name: "Joe Creator" end end end it "allows assigning traits for the factory of an association" do author = FactoryBot.create(:post).author expect(author).to be_admin expect(author.name).to eq "John Doe" end it "allows inline traits with the default association" do user = FactoryBot.create(:comment).user expect(user).to be_admin expect(user.name).to eq "Joe Slick" end it "allows inline traits with a specific factory for an association" do creator = FactoryBot.create(:order).creator expect(creator).to be_admin expect(creator.name).to eq "Joe Creator" end end describe "when a self-referential trait is defined" do it "raises a TraitDefinitionError" do define_model("User", name: :string) FactoryBot.define do factory :user do trait :admin do admin end end end expect { FactoryBot.build(:user, :admin) }.to raise_error( FactoryBot::TraitDefinitionError, "Self-referencing trait 'admin'" ) end it "raises a TraitDefinitionError" do define_model("User", name: :string) FactoryBot.define do factory :user do trait :admin do admin name { "name" } end end end expect { FactoryBot.build(:user, :admin) }.to raise_error( FactoryBot::TraitDefinitionError, "Self-referencing trait 'admin'" ) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/build_list_spec.rb
spec/acceptance/build_list_spec.rb
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
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/reload_spec.rb
spec/acceptance/reload_spec.rb
describe "reload" do it "does not reset the value of use_parent_strategy" do custom_strategy = :custom_use_parent_strategy_value with_temporary_assignment(FactoryBot, :use_parent_strategy, custom_strategy) do FactoryBot.reload expect(FactoryBot.use_parent_strategy).to eq custom_strategy end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/add_attribute_spec.rb
spec/acceptance/add_attribute_spec.rb
describe "#add_attribute" do it "assigns attributes for reserved words on .build" do define_model("Post", title: :string, sequence: :string, new: :boolean) FactoryBot.define do factory :post do add_attribute(:title) { "Title" } add_attribute(:sequence) { "Sequence" } add_attribute(:new) { true } end end post = FactoryBot.build(:post) expect(post.title).to eq "Title" expect(post.sequence).to eq "Sequence" expect(post.new).to eq true end it "assigns attributes for reserved words on .attributes_for" do define_model("Post", title: :string, sequence: :string, new: :boolean) FactoryBot.define do factory :post do add_attribute(:title) { "Title" } add_attribute(:sequence) { "Sequence" } add_attribute(:new) { true } end end post = FactoryBot.attributes_for(:post) expect(post[:title]).to eq "Title" expect(post[:sequence]).to eq "Sequence" expect(post[:new]).to eq true end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attribute_existing_on_object_spec.rb
spec/acceptance/attribute_existing_on_object_spec.rb
describe "declaring attributes on a Factory that are private methods on Object" do before do define_model("Website", system: :boolean, link: :string, sleep: :integer) FactoryBot.define do factory :website do system { false } link { "http://example.com" } sleep { 15 } end end end subject { FactoryBot.build(:website, sleep: -5) } its(:system) { should eq false } its(:link) { should eq "http://example.com" } its(:sleep) { should eq(-5) } end describe "assigning overrides that are also private methods on object" do before do define_model("Website", format: :string, y: :integer, more_format: :string, some_funky_method: :string) Object.class_eval do private def some_funky_method(args) end end FactoryBot.define do factory :website do more_format { "format: #{format}" } end end end after do Object.send(:undef_method, :some_funky_method) end subject { FactoryBot.build(:website, format: "Great", y: 12345, some_funky_method: "foobar!") } its(:format) { should eq "Great" } its(:y) { should eq 12345 } its(:more_format) { should eq "format: Great" } its(:some_funky_method) { should eq "foobar!" } end describe "accessing methods from the instance within a dynamic attribute " \ "that is also a private method on object" do before do define_model("Website", more_format: :string) do def format "This is an awesome format" end end FactoryBot.define do factory :website do more_format { "format: #{format}" } end end end subject { FactoryBot.build(:website) } its(:more_format) { should eq "format: This is an awesome format" } end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/lint_spec.rb
spec/acceptance/lint_spec.rb
describe "FactoryBot.lint" do it "raises when a factory is invalid" do define_model "User", name: :string do validates :name, presence: true end define_model "AlwaysValid" FactoryBot.define do factory :user do factory :admin_user end factory :always_valid end error_message = <<~ERROR_MESSAGE.strip The following factories are invalid: * user - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid) * admin_user - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid) ERROR_MESSAGE expect { FactoryBot.lint }.to raise_error FactoryBot::InvalidFactoryError, error_message end it "executes linting in an ActiveRecord::Base transaction" do define_model "User", name: :string do validates :name, uniqueness: true end define_model "AlwaysValid" FactoryBot.define do factory :user do factory :admin_user end factory :always_valid end expect { FactoryBot.lint }.to_not raise_error end it "runs after_commit callbacks when linting in a ActiveRecord::Base transaction" do define_model "ModelWithAfterCommitCallbacks" do class_attribute :after_commit_callbacks_received after_commit do self.class.after_commit_callbacks_received = true end end FactoryBot.define do factory :model_with_after_commit_callbacks end FactoryBot.lint expect(ModelWithAfterCommitCallbacks.after_commit_callbacks_received).to be true end it "does not raise when all factories are valid" do define_model "User", name: :string do validates :name, presence: true end FactoryBot.define do factory :user do name { "assigned" } end end expect { FactoryBot.lint }.not_to raise_error end it "allows for selective linting" do define_model "InvalidThing", name: :string do validates :name, presence: true end define_model "ValidThing", name: :string FactoryBot.define do factory :valid_thing factory :invalid_thing end expect { only_valid_factories = FactoryBot.factories.reject { |factory| factory.name =~ /invalid/ } FactoryBot.lint only_valid_factories }.not_to raise_error end describe "trait validation" do context "enabled" do it "raises if a trait produces an invalid object" do define_model "User", name: :string do validates :name, presence: true end FactoryBot.define do factory :user do name { "Yep" } trait :unnamed do name { nil } end end end error_message = <<~ERROR_MESSAGE.strip The following factories are invalid: * user+unnamed - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid) ERROR_MESSAGE expect { FactoryBot.lint traits: true }.to raise_error FactoryBot::InvalidFactoryError, error_message end it "does not raise if a trait produces a valid object" do define_model "User", name: :string do validates :name, presence: true end FactoryBot.define do factory :user do name { "Yep" } trait :renamed do name { "Yessir" } end end end expect { FactoryBot.lint traits: true }.not_to raise_error end end context "disabled" do it "does not raises if a trait produces an invalid object" do define_model "User", name: :string do validates :name, presence: true end FactoryBot.define do factory :user do name { "Yep" } trait :unnamed do name { nil } end end end expect { FactoryBot.lint traits: false FactoryBot.lint }.not_to raise_error end end end describe "factory strategy for linting" do it "uses the requested strategy" do define_class "User" do attr_accessor :name def save! raise "expected :build strategy, #save! shouldn't be invoked" end end FactoryBot.define do factory :user do name { "Barbara" } end end expect { FactoryBot.lint strategy: :build }.not_to raise_error end it "uses the requested strategy during trait validation" do define_class "User" do attr_accessor :name def save! raise "expected :build strategy, #save! shouldn't be invoked" end end FactoryBot.define do factory :user do name { "Barbara" } trait :male do name { "Bob" } end end end expect { FactoryBot.lint traits: true, strategy: :build }.not_to raise_error end end describe "verbose linting" do it "prints the backtrace for each factory error" do define_class("InvalidThing") do def save! raise "invalid" end end FactoryBot.define do factory :invalid_thing end expect { FactoryBot.lint(verbose: true) }.to raise_error( FactoryBot::InvalidFactoryError, %r{#{__FILE__}:\d*:in ('InvalidThing#save!'|`save!')} ) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/parent_spec.rb
spec/acceptance/parent_spec.rb
describe "an instance generated by a factory that inherits from another factory" do before do define_model("User", name: :string, admin: :boolean, email: :string, upper_email: :string, login: :string) FactoryBot.define do factory :user do name { "John" } email { "#{name.downcase}@example.com" } login { email } factory :admin do name { "admin" } admin { true } upper_email { email.upcase } end end end end describe "the parent class" do subject { FactoryBot.create(:user) } it { should_not be_admin } its(:name) { should eq "John" } its(:email) { should eq "john@example.com" } its(:login) { should eq "john@example.com" } end describe "the child class redefining parent's attributes" do subject { FactoryBot.create(:admin) } it { should be_kind_of(User) } it { should be_admin } its(:name) { should eq "admin" } its(:email) { should eq "admin@example.com" } its(:login) { should eq "admin@example.com" } its(:upper_email) { should eq "ADMIN@EXAMPLE.COM" } end end describe "nested factories with different parents" do before do define_model("User", name: :string) FactoryBot.define do factory :user do name { "Basic User" } factory :male_user do name { "John Doe" } end factory :uppercase_male_user, parent: :male_user do after(:build) { |user| user.name = user.name.upcase } end end end end it "honors :parent over the factory block nesting" do expect(FactoryBot.build(:uppercase_male_user).name).to eq "JOHN DOE" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/overrides_spec.rb
spec/acceptance/overrides_spec.rb
describe "attribute overrides" do before do define_model("User", admin: :boolean) define_model("Post", title: :string, secure: :boolean, user_id: :integer) do belongs_to :user def secure=(value) return unless user&.admin? write_attribute(:secure, value) end end FactoryBot.define do factory :user do factory :admin do admin { true } end end factory :post do user title { "default title" } end end end let(:admin) { FactoryBot.create(:admin) } let(:post_attributes) do {secure: false} end let(:non_admin_post_attributes) do post_attributes[:user] = FactoryBot.create(:user) post_attributes end let(:admin_post_attributes) do post_attributes[:user] = admin post_attributes end context "with an admin posting" do subject { FactoryBot.create(:post, admin_post_attributes) } its(:secure) { should eq false } end context "with a non-admin posting" do subject { FactoryBot.create(:post, non_admin_post_attributes) } its(:secure) { should be_nil } end context "with no user posting" do subject { FactoryBot.create(:post, post_attributes) } its(:secure) { should be_nil } end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/enum_traits_spec.rb
spec/acceptance/enum_traits_spec.rb
describe "enum traits" do def define_model_with_enum(class_name, field, values) define_model(class_name, status: :integer) do if ActiveRecord::VERSION::STRING >= "7.0" enum field, values else enum field => values end end end context "when automatically_define_enum_traits is true" do it "builds traits automatically for model enum field" do define_model_with_enum("Task", :status, {queued: 0, started: 1, finished: 2}) FactoryBot.define do factory :task end Task.statuses.each_key do |trait_name| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq(trait_name) end Task.reset_column_information end it "prefers user defined traits over automatically built traits" do define_model_with_enum("Task", :status, {queued: 0, started: 1, finished: 2}) FactoryBot.define do factory :task do trait :queued do status { :finished } end trait :started do status { :finished } end trait :finished do status { :finished } end end end Task.statuses.each_key do |trait_name| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq("finished") end Task.reset_column_information end it "builds traits for each enumerated value using a provided list of values as a Hash" do statuses = {queued: 0, started: 1, finished: 2} define_class "Task" do attr_accessor :status end FactoryBot.define do factory :task do traits_for_enum :status, statuses end end statuses.each do |trait_name, trait_value| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq(trait_value) end end it "builds traits for each enumerated value using a provided list of values as an Array" do statuses = %w[queued started finished] define_class "Task" do attr_accessor :status end FactoryBot.define do factory :task do traits_for_enum :status, statuses end end statuses.each do |trait_name| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq(trait_name) end end it "builds traits for each enumerated value using a custom enumerable" do statuses = define_class("Statuses") { include Enumerable def each(&block) ["queued", "started", "finished"].each(&block) end }.new define_class "Task" do attr_accessor :status end FactoryBot.define do factory :task do traits_for_enum :status, statuses end end statuses.each do |trait_name| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq(trait_name) end end end context "when automatically_define_enum_traits is false" do it "raises an error for undefined traits" do with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do define_model_with_enum("Task", :status, {queued: 0, started: 1, finished: 2}) FactoryBot.define do factory :task end Task.statuses.each_key do |trait_name| expect { FactoryBot.build(:task, trait_name) }.to raise_error( KeyError, "Trait not registered: \"#{trait_name}\"" ) end Task.reset_column_information end end it "builds traits for each enumerated value when traits_for_enum are specified" do with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do define_model_with_enum("Task", :status, {queued: 0, started: 1, finished: 2}) FactoryBot.define do factory :task do traits_for_enum(:status) end end Task.statuses.each_key do |trait_name| task = FactoryBot.build(:task, trait_name) expect(task.status).to eq(trait_name) end Task.reset_column_information end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/definition_camel_string_spec.rb
spec/acceptance/definition_camel_string_spec.rb
describe "an instance generated by a factory named a camel case string " do before do define_model("UserModel") FactoryBot.define do factory "UserModel", class: UserModel end end it "registers the UserModel factory" do expect(FactoryBot::Internal.factory_by_name("UserModel")) .to be_a(FactoryBot::Factory) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/global_initialize_with_spec.rb
spec/acceptance/global_initialize_with_spec.rb
describe "global initialize_with" do before do define_class("User") do attr_accessor :name def initialize(name) @name = name end end define_class("Post") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do initialize_with { new("initialize_with") } trait :with_initialize_with do initialize_with { new("trait initialize_with") } end factory :user do factory :child_user factory :child_user_with_trait do with_initialize_with end end factory :post do factory :child_post factory :child_post_with_trait do with_initialize_with end end end end it "handles base initialize_with" do expect(FactoryBot.build(:user).name).to eq "initialize_with" expect(FactoryBot.build(:post).name).to eq "initialize_with" end it "handles child initialize_with" do expect(FactoryBot.build(:child_user).name).to eq "initialize_with" expect(FactoryBot.build(:child_post).name).to eq "initialize_with" end it "handles child initialize_with with trait" do expect(FactoryBot.build(:child_user_with_trait).name).to eq "trait initialize_with" expect(FactoryBot.build(:child_post_with_trait).name).to eq "trait initialize_with" end it "handles inline trait override" do expect(FactoryBot.build(:child_user, :with_initialize_with).name).to eq "trait initialize_with" expect(FactoryBot.build(:child_post, :with_initialize_with).name).to eq "trait initialize_with" end it "uses initialize_with globally across FactoryBot.define" do define_class("Company") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :company end expect(FactoryBot.build(:company).name).to eq "initialize_with" expect(FactoryBot.build(:company, :with_initialize_with).name).to eq "trait initialize_with" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/sequence_setting_spec.rb
spec/acceptance/sequence_setting_spec.rb
describe "FactoryBot.set_sequence" do include FactoryBot::Syntax::Methods describe "on success" do describe "setting sequence to correct value" do it "works with Integer sequences" do FactoryBot.define do sequence(:email) { |n| "somebody#{n}@example.com" } end expect(generate_list(:email, 3).last).to eq "somebody3@example.com" FactoryBot.set_sequence(:email, 54321) expect(generate_list(:email, 3).last).to eq "somebody54323@example.com" end it "works with negative Integer sequences" do FactoryBot.define do sequence(:email, -50) { |n| "somebody#{n}@example.com" } end expect(generate_list(:email, 3).last).to eq "somebody-48@example.com" FactoryBot.set_sequence(:email, -25) expect(generate_list(:email, 3).last).to eq "somebody-23@example.com" end it "works with Enumerable sequences" do define_class("User") { attr_accessor :name } FactoryBot.define do factory :user do sequence(:name, %w[Jane Joe Josh Jayde John].to_enum) end end expect(generate(:user, :name)).to eq "Jane" FactoryBot.set_sequence(:user, :name, "Jayde") expect(generate(:user, :name)).to eq "Jayde" expect(generate(:user, :name)).to eq "John" end it "works with String sequences" do define_class("User") { attr_accessor :initial } FactoryBot.define do factory :user do factory :pilot do sequence(:initial, "a") end end end expect(generate_list(:pilot, :initial, 3)).to eq ["a", "b", "c"] FactoryBot.set_sequence(:pilot, :initial, "z") expect(generate_list(:pilot, :initial, 3)).to eq ["z", "aa", "ab"] end it "works with Date sequences" do define_class("User") { attr_accessor :dob } FactoryBot.define do factory :user do factory :pilot do factory :jet_pilot do sequence(:dob, Date.parse("2025-04-01")) end end end end expect(generate(:jet_pilot, :dob)).to eq Date.parse("2025-04-01") FactoryBot.set_sequence(:jet_pilot, :dob, Date.parse("2025-05-01")) expect(generate_list(:jet_pilot, :dob, 3).last).to eq Date.parse("2025-05-03") end it "works with lazy Integer sequences" do FactoryBot.define do sequence(:email, proc { 42 }) { |n| "somebody#{n}@example.com" } end expect(generate_list(:email, 3).last).to eq "somebody44@example.com" FactoryBot.set_sequence(:email, 54321) expect(generate_list(:email, 3).last).to eq "somebody54323@example.com" end it "does not collide with other factory or global sequences" do define_class("User") { attr_accessor :email } define_class("Admin") { attr_accessor :email } FactoryBot.define do sequence(:email) { |n| "global#{n}@example.com" } factory :user do sequence(:email) { |n| "user#{n}@example.com" } factory :admin do sequence(:email) { |n| "admin#{n}@example.com" } end end end generate_list :email, 2 generate_list :user, :email, 2 generate_list :admin, :email, 2 expect(generate(:email)).to eq "global3@example.com" expect(generate(:user, :email)).to eq "user3@example.com" expect(generate(:admin, :email)).to eq "admin3@example.com" FactoryBot.set_sequence(:user, :email, 22222) FactoryBot.set_sequence(:admin, :email, 33333) expect(generate(:email)).to eq "global4@example.com" expect(generate(:user, :email)).to eq "user22222@example.com" expect(generate(:admin, :email)).to eq "admin33333@example.com" end end describe "sequence targeting by URI" do before do define_class("User") FactoryBot.define do sequence :counter trait :global_trait do sequence :counter end factory :parent, class: "User" do sequence :counter trait :parent_trait do sequence :counter end factory :child do sequence :counter trait :child_trait do sequence :counter end end end end end it "accepts symbolic URIs" do expect(generate(:counter)).to eq 1 expect(generate(:global_trait, :counter)).to eq 1 expect(generate(:parent, :counter)).to eq 1 expect(generate(:parent, :parent_trait, :counter)).to eq 1 expect(generate(:child, :counter)).to eq 1 expect(generate(:child, :child_trait, :counter)).to eq 1 FactoryBot.set_sequence :counter, 1000 FactoryBot.set_sequence :global_trait, :counter, 3000 FactoryBot.set_sequence :parent, :counter, 6000 FactoryBot.set_sequence :parent, :parent_trait, :counter, 9000 FactoryBot.set_sequence :child, :counter, 12_000 FactoryBot.set_sequence :child, :child_trait, :counter, 15_000 expect(generate(:counter)).to eq 1000 expect(generate(:global_trait, :counter)).to eq 3000 expect(generate(:parent, :counter)).to eq 6000 expect(generate(:parent, :parent_trait, :counter)).to eq 9000 expect(generate(:child, :counter)).to eq 12_000 expect(generate(:child, :child_trait, :counter)).to eq 15_000 end it "accepts string URIs" do expect(generate("counter")).to eq 1 expect(generate("global_trait/counter")).to eq 1 expect(generate("parent/counter")).to eq 1 expect(generate("parent/parent_trait/counter")).to eq 1 expect(generate("child/counter")).to eq 1 expect(generate("child/child_trait/counter")).to eq 1 FactoryBot.set_sequence "counter", 1000 FactoryBot.set_sequence "global_trait/counter", 3000 FactoryBot.set_sequence "parent/counter", 6000 FactoryBot.set_sequence "parent/parent_trait/counter", 9000 FactoryBot.set_sequence "child/counter", 12_000 FactoryBot.set_sequence "child/child_trait/counter", 15_000 expect(generate("counter")).to eq 1000 expect(generate("global_trait/counter")).to eq 3000 expect(generate("parent/counter")).to eq 6000 expect(generate("parent/parent_trait/counter")).to eq 9000 expect(generate("child/counter")).to eq 12_000 expect(generate("child/child_trait/counter")).to eq 15_000 end end describe "name format support" do it "accepts String or Symbol sequence names" do FactoryBot.define do sequence(:email) { |n| "user#{n}@example.com" } end FactoryBot.set_sequence(:email, 54321) expect(generate(:email)).to eq "user54321@example.com" FactoryBot.set_sequence("email", 777) expect(generate(:email)).to eq "user777@example.com" end it "accepts String or Symbol factory names" do define_class("User") { attr_accessor :email } FactoryBot.define do factory :user do sequence(:email) { |n| "user#{n}@example.com" } end end FactoryBot.set_sequence(:user, :email, 54321) expect(generate(:user, :email)).to eq "user54321@example.com" FactoryBot.set_sequence("user", "email", 777) expect(generate("user", "email")).to eq "user777@example.com" end end describe "alias support" do it "works with aliases for both sequence and factory" do define_class("User") { attr_accessor :email } FactoryBot.define do factory :user, aliases: [:author, :commenter] do sequence(:email, aliases: ["primary_email", :alt_email]) { |n| "user#{n}@example.com" } end end generate_list :user, :email, 2 expect(generate(:user, :email)).to eq "user3@example.com" FactoryBot.set_sequence(:user, :email, 11111) expect(generate(:user, :email)).to eq "user11111@example.com" FactoryBot.set_sequence(:author, :primary_email, 22222) expect(generate(:user, :email)).to eq "user22222@example.com" FactoryBot.set_sequence(:commenter, :alt_email, 33333) expect(generate(:user, :email)).to eq "user33333@example.com" end end end describe "error handling" do describe "unknown sequence names" do it "raises an error for unknown global sequences" do expect { FactoryBot.set_sequence(:test, 54321) } .to raise_error KeyError, /Sequence not registered: 'test'/ end it "raises an error for unknown factory sequences" do FactoryBot.define do factory :user do sequence(:email) { |n| "alt_user#{n}@example.com" } end end expect { FactoryBot.set_sequence(:user, :test, 54321) } .to raise_error KeyError, /Sequence not registered: 'user\/test'/ end it "raises an error when factory sequence doesn't exist but global does" do FactoryBot.define do sequence(:email) { |n| "global#{n}@example.com" } factory :user do sequence(:alt_email) { |n| "alt_user#{n}@example.com" } end end expect { FactoryBot.set_sequence(:user, :email, 54321) } .to raise_error KeyError, /Sequence not registered: 'user\/email'/ end it "raises an error for inherited sequences" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:email) { |n| "global#{n}@example.com" } factory :user do sequence(:email) { |n| "user#{n}@example.com" } factory :admin end end admin = build(:admin) expect(admin.email).to eq "user1@example.com" expect { FactoryBot.set_sequence(:admin, :email, 54321) } .to raise_error KeyError, /Sequence not registered: 'admin\/email'/ end end describe "invalid values" do it "raises an error when value is below minimum for Integer sequences" do FactoryBot.define do sequence(:counter, 1000) end expect { FactoryBot.set_sequence(:counter, 999) } .to raise_error ArgumentError, /Value cannot be less than: 1000/ end it "raises an error for unmatched String values", :slow do FactoryBot.define do sequence(:char, "c") end expect { FactoryBot.set_sequence(:char, "a") } .to raise_error ArgumentError, /Unable to find 'a' in the sequence/ end it "raises an error for unmatched Enumerable values" do names = %w[Jane Joe Josh Jayde John].to_enum allow_any_instance_of(FactoryBot::Sequence).to receive(:can_set_value_by_index?).and_return(false) FactoryBot.define do sequence(:name, names) end expect { FactoryBot.set_sequence(:name, "Jester") } .to raise_error ArgumentError, /Unable to find 'Jester' in the sequence/ end it "times out when value cannot be found within timeout period", :slow do with_temporary_assignment(FactoryBot, :sequence_setting_timeout, 3) do FactoryBot.define do sequence(:test, "a") end start = Time.now expect { FactoryBot.set_sequence(:test, "zzzzzzzzzz") } .to raise_error ArgumentError, /Unable to find 'zzzzzzzzzz' in the sequence/ duration = Time.now - start expect(duration >= 3.seconds).to be_truthy expect(duration < 4.seconds).to be_truthy end end it "leaves sequence unchanged when value is not found" do FactoryBot.define do sequence(:name, %w[Jane Joe Josh Jayde John].to_enum) end generate_list :name, 2 expect(generate(:name)).to eq "Josh" expect { FactoryBot.set_sequence(:name, "Jester") } .to raise_error ArgumentError, /Unable to find 'Jester' in the sequence/ expect(generate(:name)).to eq "Jayde" end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/defining_methods_inside_a_factory_spec.rb
spec/acceptance/defining_methods_inside_a_factory_spec.rb
describe "defining methods inside FactoryBot" do it "raises with a meaningful message" do define_model("User") bad_factory_definition = -> do FactoryBot.define do factory :user do def generate_name "John Doe" end end end end expect(&bad_factory_definition).to raise_error( FactoryBot::MethodDefinitionError, /Defining methods in blocks \(trait or factory\) is not supported \(generate_name\)/ ) end it "accepts a method named :definition when set through :method_missing" do define_model("User", definition: :string) FactoryBot.define do factory :user do definition do "Jester" end end end user = FactoryBot.build(:user) expect(user.definition).to eq("Jester") end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/global_to_create_spec.rb
spec/acceptance/global_to_create_spec.rb
describe "global to_create" do before do define_model("User", name: :string) define_model("Post", name: :string) FactoryBot.define do to_create { |instance| instance.name = "persisted!" } trait :override_to_create do to_create { |instance| instance.name = "override" } end factory :user do name { "John Doe" } factory :child_user factory :child_user_with_trait do override_to_create end end factory :post do name { "Great title" } factory :child_post factory :child_post_with_trait do override_to_create end end end end it "handles base to_create" do expect(FactoryBot.create(:user).name).to eq "persisted!" expect(FactoryBot.create(:post).name).to eq "persisted!" end it "handles child to_create" do expect(FactoryBot.create(:child_user).name).to eq "persisted!" expect(FactoryBot.create(:child_post).name).to eq "persisted!" end it "handles child to_create with trait" do expect(FactoryBot.create(:child_user_with_trait).name).to eq "override" expect(FactoryBot.create(:child_post_with_trait).name).to eq "override" end it "handles inline trait override" do user = FactoryBot.create(:child_user, :override_to_create) post = FactoryBot.create(:child_post, :override_to_create) expect(user.name).to eq "override" expect(post.name).to eq "override" end it "uses to_create globally across FactoryBot.define" do define_model("Company", name: :string) FactoryBot.define do factory :company end company = FactoryBot.create(:company) override_company = FactoryBot.create(:company, :override_to_create) expect(company.name).to eq "persisted!" expect(override_company.name).to eq "override" end end describe "global skip_create" do before do define_model("User", name: :string) define_model("Post", name: :string) FactoryBot.define do skip_create trait :override_to_create do to_create { |instance| instance.name = "override" } end factory :user do name { "John Doe" } factory :child_user factory :child_user_with_trait do override_to_create end end factory :post do name { "Great title" } factory :child_post factory :child_post_with_trait do override_to_create end end end end it "does not persist any record" do expect(FactoryBot.create(:user)).to be_new_record expect(FactoryBot.create(:post)).to be_new_record end it "does not persist child records" do expect(FactoryBot.create(:child_user)).to be_new_record expect(FactoryBot.create(:child_post)).to be_new_record end it "honors overridden to_create" do expect(FactoryBot.create(:child_user_with_trait).name).to eq "override" expect(FactoryBot.create(:child_post_with_trait).name).to eq "override" end it "honors inline trait to_create" do expect(FactoryBot.create(:child_user, :override_to_create).name).to eq "override" expect(FactoryBot.create(:child_post, :override_to_create).name).to eq "override" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/create_list_spec.rb
spec/acceptance/create_list_spec.rb
describe "create 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.create_list(:post, 20) } its(:length) { should eq 20 } 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 context "with default attributes" do subject { FactoryBot.create_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.create_list(:post, 20, title: "The Listing of the Block") do |post| post.position = post.id end end it "uses the new values" 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.create_list(:post, 20, title: "The Indexed Block") do |post, index| post.position = index end end it "uses the new values" do subject.each_with_index do |record, index| expect(record.position).to eq index end end end context "without the count" do subject { FactoryBot.create_list(:post, title: "The Hunting of the Bear") } it "raise ArgumentError with the proper error message" do expect { subject }.to raise_error(ArgumentError, /count missing/) end end end describe "multiple creates and transient attributes to dynamically build attribute lists" do before do define_model("User", name: :string) do has_many :posts end define_model("Post", title: :string, user_id: :integer) do belongs_to :user end FactoryBot.define do factory :post do title { "Through the Looking Glass" } user end factory :user do name { "John Doe" } factory :user_with_posts do transient do posts_count { 5 } end after(:create) do |user, evaluator| FactoryBot.create_list(:post, evaluator.posts_count, user: user) end end end end end it "generates the correct number of posts" do expect(FactoryBot.create(:user_with_posts).posts.length).to eq 5 end it "allows the number of posts to be modified" do expect(FactoryBot.create(:user_with_posts, posts_count: 2).posts.length).to eq 2 end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/private_attributes_spec.rb
spec/acceptance/private_attributes_spec.rb
describe "setting private attributes" do it "raises a NoMethodError" do define_class("User") do private attr_accessor :foo end FactoryBot.define do factory :user do foo { 123 } end end expect { FactoryBot.build(:user) }.to raise_error NoMethodError, /foo=/ end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/initialize_with_spec.rb
spec/acceptance/initialize_with_spec.rb
describe "initialize_with with non-FG attributes" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string, age: :integer) do def self.construct(name, age) new(name: name, age: age) end end FactoryBot.define do factory :user do initialize_with { User.construct("John Doe", 21) } end end end subject { build(:user) } its(:name) { should eq "John Doe" } its(:age) { should eq 21 } end describe "initialize_with with FG attributes that are transient" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string) do def self.construct(name) new(name: "#{name} from .construct") end end FactoryBot.define do factory :user do transient do name { "Handsome Chap" } end initialize_with { User.construct(name) } end end end subject { build(:user) } its(:name) { should eq "Handsome Chap from .construct" } end describe "initialize_with non-ORM-backed objects" do include FactoryBot::Syntax::Methods before do define_class("ReportGenerator") do attr_reader :name, :data def initialize(name, data) @name = name @data = data end end FactoryBot.define do sequence(:random_data) { Array.new(5) { Kernel.rand(200) } } factory :report_generator do transient do name { "My Awesome Report" } end initialize_with { ReportGenerator.new(name, FactoryBot.generate(:random_data)) } end end end it "allows for overrides" do expect(build(:report_generator, name: "Overridden").name).to eq "Overridden" end it "generates random data" do expect(build(:report_generator).data.length).to eq 5 end end describe "initialize_with parent and child factories" do before do define_class("Awesome") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :awesome do transient do name { "Great" } end initialize_with { Awesome.new(name) } factory :sub_awesome do transient do name { "Sub" } end end factory :super_awesome do initialize_with { Awesome.new("Super") } end end end end it "uses the parent's constructor when the child factory doesn't assign it" do expect(FactoryBot.build(:sub_awesome).name).to eq "Sub" end it "allows child factories to override initialize_with" do expect(FactoryBot.build(:super_awesome).name).to eq "Super" end end describe "initialize_with implicit constructor" do before do define_class("Awesome") do attr_reader :name def initialize(name) @name = name end end FactoryBot.define do factory :awesome do transient do name { "Great" } end initialize_with { new(name) } end end end it "instantiates the correct object" do expect(FactoryBot.build(:awesome, name: "Awesome name").name).to eq "Awesome name" end end describe "initialize_with doesn't duplicate assignment on attributes accessed from initialize_with" do before do define_class("User") do attr_reader :name attr_accessor :email def initialize(name) @name = name end end FactoryBot.define do sequence(:email) { |n| "person#{n}@example.com" } factory :user do email name { email.gsub(/@.+/, "") } initialize_with { new(name) } end end end it "instantiates the correct object" do built_user = FactoryBot.build(:user) expect(built_user.name).to eq "person1" expect(built_user.email).to eq "person1@example.com" end end describe "initialize_with has access to all attributes for construction" do it "assigns attributes correctly" do define_class("User") do attr_reader :name, :email, :ignored def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] @ignored = attributes[:ignored] end end FactoryBot.define do sequence(:email) { |n| "person#{n}@example.com" } factory :user do transient do ignored { "of course!" } end email name { email.gsub(/@.+/, "") } initialize_with { new(**attributes) } end end user_with_attributes = FactoryBot.build(:user) expect(user_with_attributes.email).to eq "person1@example.com" expect(user_with_attributes.name).to eq "person1" expect(user_with_attributes.ignored).to be_nil end end describe "initialize_with with an 'attributes' attribute" do it "assigns attributes correctly" do define_class("User") do attr_reader :name def initialize(attributes:) @name = attributes[:name] end end FactoryBot.define do factory :user do attributes { {name: "Daniel"} } initialize_with { new(**attributes) } end end user = FactoryBot.build(:user) expect(user.name).to eq("Daniel") end end describe "initialize_with for a constructor that requires a block" do it "executes the block correctly" do define_class("Awesome") do attr_reader :output def initialize(&block) @output = instance_exec(&block) end end FactoryBot.define do factory :awesome do initialize_with { new { "Output" } } end end expect(FactoryBot.build(:awesome).output).to eq "Output" end end describe "initialize_with with a hash argument" do it "builds the object correctly" do define_class("Container") do attr_reader :contents def initialize(contents) @contents = contents end end FactoryBot.define do factory :container do initialize_with { new({key: :value}) } end end expect(FactoryBot.build(:container).contents).to eq({key: :value}) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/definition_spec.rb
spec/acceptance/definition_spec.rb
describe "an instance generated by a factory with a custom class name" do before do define_model("User", admin: :boolean) FactoryBot.define do factory :user factory :admin, class: User do admin { true } end end end subject { FactoryBot.create(:admin) } it { should be_kind_of(User) } it { should be_admin } end describe "attributes defined using Symbol#to_proc" do before do define_model("User", password: :string, password_confirmation: :string) FactoryBot.define do factory :user do password { "foo" } password_confirmation(&:password) end end end it "assigns values correctly" do user = FactoryBot.build(:user) expect(user.password).to eq "foo" expect(user.password_confirmation).to eq "foo" end it "assigns value with override correctly" do user = FactoryBot.build(:user, password: "bar") expect(user.password).to eq "bar" expect(user.password_confirmation).to eq "bar" end it "assigns overridden value correctly" do user = FactoryBot.build(:user, password_confirmation: "bar") expect(user.password).to eq "foo" expect(user.password_confirmation).to eq "bar" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/associations_spec.rb
spec/acceptance/associations_spec.rb
describe "associations" do context "when accidentally using an implicit declaration for the factory" do it "raises an error" do define_class("Post") FactoryBot.define do factory :post do author factory: user end end expect { FactoryBot.build(:post) }.to raise_error( ArgumentError, "Association 'author' received an invalid factory argument.\n" \ "Did you mean? 'factory: :user'\n" ) end end context "when accidentally using an implicit declaration as an override" do it "raises an error" do define_class("Post") FactoryBot.define do factory :post do author factory: :user, invalid_attribute: implicit_trait end end expect { FactoryBot.build(:post) }.to raise_error( ArgumentError, "Association 'author' received an invalid attribute override.\n" \ "Did you mean? 'invalid_attribute: :implicit_trait'\n" ) end end context "when building interrelated associations" do it "assigns the instance passed as an association attribute" do define_class("Supplier") do attr_accessor :account end define_class("Account") do attr_accessor :supplier end FactoryBot.define do factory :supplier factory :account do supplier { association(:supplier, account: instance) } end end account = FactoryBot.build(:account) expect(account.supplier.account).to eq(account) end it "connects records with interdependent relationships" do define_model("Student", school_id: :integer) do belongs_to :school has_one :profile end define_model("Profile", school_id: :integer, student_id: :integer) do belongs_to :school belongs_to :student end define_model("School") do has_many :students has_many :profiles end FactoryBot.define do factory :student do school profile { association :profile, student: instance, school: school } end factory :profile do school student { association :student, profile: instance, school: school } end factory :school end student = FactoryBot.create(:student) expect(student.profile.school).to eq(student.school) expect(student.profile.student).to eq(student) expect(student.school.students.map(&:id)).to eq([student.id]) expect(student.school.profiles.map(&:id)).to eq([student.profile.id]) profile = FactoryBot.create(:profile) expect(profile.student.school).to eq(profile.school) expect(profile.student.profile).to eq(profile) expect(profile.school.profiles.map(&:id)).to eq([profile.id]) expect(profile.school.students.map(&:id)).to eq([profile.student.id]) end end context "when building collection associations" do it "builds the association according to the given strategy" do define_model("Photo", listing_id: :integer) do belongs_to :listing attr_accessor :name end define_model("Listing") do has_many :photos end FactoryBot.define do factory :photo factory :listing do photos { [association(:photo)] } end end created_listing = FactoryBot.create(:listing) expect(created_listing.photos.first).to be_a Photo expect(created_listing.photos.first).to be_persisted built_listing = FactoryBot.build(:listing) expect(built_listing.photos.first).to be_a Photo expect(built_listing.photos.first).not_to be_persisted stubbed_listing = FactoryBot.build_stubbed(:listing) expect(stubbed_listing.photos.first).to be_a Photo expect(stubbed_listing.photos.first).to be_persisted expect { stubbed_listing.photos.first.save! }.to raise_error( "stubbed models are not allowed to access the database - Photo#save!()" ) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/sequence_spec.rb
spec/acceptance/sequence_spec.rb
describe "sequences" do include FactoryBot::Syntax::Methods require "ostruct" # = On Success # ====================================================================== # describe "on success" do it "generates several values in the correct format" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:email) { |n| "global-#{n}@example.com" } factory :user do sequence(:email) { |n| "user-#{n}@example.com" } end end expect(generate(:email)).to eq "global-1@example.com" expect(generate(:email)).to eq "global-2@example.com" expect(generate(:email)).to eq "global-3@example.com" expect(generate(:user, :email)).to eq "user-1@example.com" expect(generate(:user, :email)).to eq "user-2@example.com" expect(generate(:user, :email)).to eq "user-3@example.com" end it "generates sequential numbers if no block is given" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence :global_order factory :user do sequence :user_order end end expect(generate(:global_order)).to eq 1 expect(generate(:global_order)).to eq 2 expect(generate(:global_order)).to eq 3 expect(generate(:user, :user_order)).to eq 1 expect(generate(:user, :user_order)).to eq 2 expect(generate(:user, :user_order)).to eq 3 end it "generates aliases for the sequence that reference the same block" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:size, aliases: [:count, :length]) { |n| "global-called-#{n}" } factory :user, aliases: [:author, :commenter] do sequence(:size, aliases: [:count, :length]) { |n| "user-called-#{n}" } end end expect(generate(:size)).to eq "global-called-1" expect(generate(:count)).to eq "global-called-2" expect(generate(:length)).to eq "global-called-3" expect(generate(:user, :size)).to eq "user-called-1" expect(generate(:author, :count)).to eq "user-called-2" expect(generate(:commenter, :length)).to eq "user-called-3" end it "generates aliases for the sequence that reference the same block and retains value" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:size, "a", aliases: [:count, :length]) { |n| "global-called-#{n}" } factory :user, aliases: [:author, :commenter] do sequence(:size, "x", aliases: [:count, :length]) { |n| "user-called-#{n}" } end end expect(generate(:size)).to eq "global-called-a" expect(generate(:count)).to eq "global-called-b" expect(generate(:length)).to eq "global-called-c" expect(generate(:user, :size)).to eq "user-called-x" expect(generate(:author, :count)).to eq "user-called-y" expect(generate(:commenter, :length)).to eq "user-called-z" end it "generates sequences after lazy loading an initial value from a proc" do loaded = false FactoryBot.define do sequence :count, proc { loaded = true "d" } end expect(loaded).to be false first_value = generate(:count) another_value = generate(:count) expect(loaded).to be true expect(first_value).to eq "d" expect(another_value).to eq "e" end it "generates sequences after lazy loading an initial value from an object responding to call" do define_class("HasCallMethod") do def initialise @called = false end def called? @called end def call @called = true "ABC" end end has_call_method_instance = HasCallMethod.new FactoryBot.define do sequence :letters, has_call_method_instance end expect(has_call_method_instance).not_to be_called first_value = generate(:letters) another_value = generate(:letters) expect(has_call_method_instance).to be_called expect(first_value).to eq "ABC" expect(another_value).to eq "ABD" end it "generates few values of the sequence" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:email) { |n| "global-#{n}@example.com" } factory :user do sequence(:email) { |n| "user-#{n}@example.com" } end end global_values = generate_list(:email, 3) expect(global_values[0]).to eq "global-1@example.com" expect(global_values[1]).to eq "global-2@example.com" expect(global_values[2]).to eq "global-3@example.com" user_values = generate_list(:user, :email, 3) expect(user_values[0]).to eq "user-1@example.com" expect(user_values[1]).to eq "user-2@example.com" expect(user_values[2]).to eq "user-3@example.com" end it "generates few values of the sequence with a given scope" do define_class("User") { attr_accessor :name, :email } FactoryBot.define do factory :user do sequence(:email) { |n| "#{name}-#{n}@example.com" } end end test_scope = OpenStruct.new(name: "Jester") user_values = generate_list(:user, :email, 3, scope: test_scope) expect(user_values[0]).to eq "Jester-1@example.com" expect(user_values[1]).to eq "Jester-2@example.com" expect(user_values[2]).to eq "Jester-3@example.com" end end # "on success" # = On Failure # ====================================================================== # describe "on failure" do it "it fails with an unknown sequence or factory name" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence :counter factory :user do sequence counter end end expect { generate(:test).to raise_error KeyError, /Sequence not registered: :test/ } expect { generate(:user, :test).to raise_error KeyError, /Sequence not registered: user:test/ } expect { generate(:admin, :counter).to raise_error KeyError, /Sequence not registered: "admin:counter"/ } end it "it fails with a sequence that references a scoped attribute, but no scope given" do define_class("User") { attr_accessor :name, :age, :info } FactoryBot.define do factory :user do sequence(:info) { |n| "#{name}:#{age + n}" } end end jester = FactoryBot.build(:user, name: "Jester", age: 21) expect(generate(:user, :info, scope: jester)).to eq "Jester:23" expect { generate(:user, :info) } .to raise_error ArgumentError, "Sequence 'user/info' failed to return a value. " \ "Perhaps it needs a scope to operate? (scope: <object>)" end end # "on failure" end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attributes_for_spec.rb
spec/acceptance/attributes_for_spec.rb
if RUBY_ENGINE != "truffleruby" require_relative "attributes_for_destructuring" end describe "a generated attributes hash" do include FactoryBot::Syntax::Methods before do define_model("User") define_model("Comment") define_model("Post", title: :string, body: :string, summary: :string, user_id: :integer) do belongs_to :user has_many :comments end FactoryBot.define do factory :user factory :comment factory :post do title { "default title" } body { "default body" } summary { title } user comments do |c| [c.association(:comment)] end end end end subject { attributes_for(:post, title: "overridden title") } it "assigns an overridden value" do expect(subject[:title]).to eq "overridden title" end it "assigns a default value" do expect(subject[:body]).to eq "default body" end it "assigns a lazy, dependent attribute" do expect(subject[:summary]).to eq "overridden title" end it "doesn't assign associations" do expect(subject).not_to have_key(:user_id) expect(subject).not_to have_key(:user) end end describe "calling `attributes_for` with a block" do include FactoryBot::Syntax::Methods before do define_model("Company", name: :string) FactoryBot.define do factory :company end end it "passes the hash of attributes" do attributes_for(:company, name: "thoughtbot") do |attributes| expect(attributes[:name]).to eq("thoughtbot") end end it "returns the hash of attributes" do expected = nil result = attributes_for(:company) { |attributes| expected = attributes "hello!" } expect(result).to eq expected end end describe "`attributes_for` for a class whose constructor has required params" do before do define_model("User", name: :string) do def initialize(arg1, arg2) # Constructor requesting params to be used for testing end end FactoryBot.define do factory :user do name { "John Doe" } end end end subject { FactoryBot.attributes_for(:user) } its([:name]) { should eq "John Doe" } end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/skip_create_spec.rb
spec/acceptance/skip_create_spec.rb
describe "skipping the default create" do before do define_model("User", email: :string) FactoryBot.define do factory :user do skip_create email { "john@example.com" } end end end it "doesn't execute anything when creating the instance" do expect(FactoryBot.create(:user)).not_to be_persisted end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/create_pair_spec.rb
spec/acceptance/create_pair_spec.rb
describe "create 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.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
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/build_stubbed_spec.rb
spec/acceptance/build_stubbed_spec.rb
describe "a generated stub instance" do include FactoryBot::Syntax::Methods before do define_model("User") define_model("Post", title: :string, body: :string, age: :integer, user_id: :integer, draft: :boolean) do belongs_to :user end FactoryBot.define do factory :user factory :post do title { "default title" } body { "default body" } user end end end subject { build_stubbed(:post, title: "overridden title") } it "assigns a default attribute" do expect(subject.body).to eq "default body" end it "assigns an overridden attribute" do expect(subject.title).to eq "overridden title" end it "assigns associations" do expect(subject.user).to be_kind_of(User) end it "has an id" do expect(subject.id).to be > 0 end it "generates unique ids" do other_stub = build_stubbed(:post) expect(subject.id).not_to eq other_stub.id end it "isn't a new record" do expect(subject).not_to be_new_record end it "assigns associations that aren't new records" do expect(subject.user).not_to be_new_record end it "isn't changed" do expect(subject).not_to be_changed end it "disables connection" do expect { subject.connection }.to raise_error(RuntimeError) end it "disables update_attribute" do expect { subject.update_attribute(:title, "value") }.to raise_error(RuntimeError) end it "disables reload" do expect { subject.reload }.to raise_error(RuntimeError) end it "disables destroy" do expect { subject.destroy }.to raise_error(RuntimeError) end it "disables save" do expect { subject.save }.to raise_error(RuntimeError) end it "disables increment!" do expect { subject.increment!(:age) }.to raise_error(RuntimeError) end it "disables decrement!" do expect { subject.decrement!(:age) }.to raise_error(RuntimeError) end it "disables toggle!" do expect { subject.toggle!(:draft) }.to raise_error(RuntimeError) end it "allows increment" do subject.age = 1 subject.increment(:age) expect(subject.age).to eq(2) end it "allows decrement" do subject.age = 1 subject.decrement(:age) expect(subject.age).to eq(0) end it "allows toggle" do subject.draft = true subject.toggle(:draft) expect(subject).not_to be_draft end end describe "calling `build_stubbed` with a block" do include FactoryBot::Syntax::Methods before do define_model("Company", name: :string) FactoryBot.define do factory :company end end it "passes the stub instance" do build_stubbed(:company, name: "thoughtbot") do |company| expect(company.name).to eq("thoughtbot") expect { company.save }.to raise_error(RuntimeError) end end it "returns the stub instance" do expected = nil result = build_stubbed(:company) { |company| expected = company "hello!" } expect(result).to eq expected end end describe "defaulting `created_at`" do include FactoryBot::Syntax::Methods before do define_model("ThingWithTimestamp", created_at: :datetime) define_model("ThingWithoutTimestamp") FactoryBot.define do factory :thing_with_timestamp factory :thing_without_timestamp end end it "defaults created_at for objects with created_at" do expect(build_stubbed(:thing_with_timestamp).created_at).to be_about_now end it "is doesn't mark the object as changed" do stub = build_stubbed(:thing_with_timestamp) expect(stub).not_to be_changed end it "doesn't add created_at to objects who don't have the method" do expect(build_stubbed(:thing_without_timestamp)) .not_to respond_to(:created_at) end it "allows overriding created_at for objects with created_at" do created_at = 3.days.ago stubbed = build_stubbed(:thing_with_timestamp, created_at: created_at) expect(stubbed.created_at).to be_within(1.second).of created_at end it "doesn't allow setting created_at on an object that doesn't define it" do expect { build_stubbed(:thing_without_timestamp, created_at: Time.now) } .to raise_error(NoMethodError, /created_at=/) end it "allows assignment of created_at" do stub = build_stubbed(:thing_with_timestamp) expect(stub.created_at).to be_about_now past_time = 3.days.ago stub.created_at = past_time expect(stub.created_at).to be_within(1.second).of past_time end it "behaves the same as a non-stubbed created_at" do define_model("ThingWithCreatedAt", created_at: :datetime) do def created_at :the_real_created_at end end FactoryBot.define do factory :thing_with_created_at end stub = build_stubbed(:thing_with_created_at) persisted = create(:thing_with_created_at) expect(stub.created_at).to eq(persisted.created_at) end end describe "defaulting `updated_at`" do include FactoryBot::Syntax::Methods before do define_model("ThingWithTimestamp", updated_at: :datetime) define_model("ThingWithoutTimestamp") FactoryBot.define do factory :thing_with_timestamp factory :thing_without_timestamp end end it "defaults updated_at for objects with updated_at" do expect(build_stubbed(:thing_with_timestamp).updated_at).to be_about_now end it "is doesn't mark the object as changed" do stub = build_stubbed(:thing_with_timestamp) expect(stub).not_to be_changed end it "doesn't add updated_at to objects who don't have the method" do expect(build_stubbed(:thing_without_timestamp)) .not_to respond_to(:updated_at) end it "allows overriding updated_at for objects with updated_at" do past_time = 3.days.ago stubbed = build_stubbed(:thing_with_timestamp, updated_at: past_time) expect(stubbed.updated_at).to be_within(1.second).of past_time end it "doesn't allow setting updated_at on an object that doesn't define it" do expect { build_stubbed(:thing_without_timestamp, updated_at: Time.now) }.to raise_error(NoMethodError, /updated_at=/) end it "allows assignment of updated_at" do stub = build_stubbed(:thing_with_timestamp) expect(stub.updated_at).to be_about_now past_time = 3.days.ago stub.updated_at = past_time expect(stub.updated_at).to be_within(1.second).of past_time end it "behaves the same as a non-stubbed updated_at" do define_model("ThingWithUpdatedAt", updated_at: :datetime) do def updated_at :the_real_updated_at end end FactoryBot.define do factory :thing_with_updated_at end stub = build_stubbed(:thing_with_updated_at) persisted = create(:thing_with_updated_at) expect(stub.updated_at).to eq(persisted.updated_at) end end describe "defaulting `id`" do before do define_model("Post") FactoryBot.define do factory :post end end it "allows overriding id" do expect(FactoryBot.build_stubbed(:post, id: 12).id).to eq 12 end end describe "configuring the starting id" do it "defines which id build_stubbed instances start with" do define_model("Post") FactoryBot.define do factory :post end FactoryBot.build_stubbed_starting_id = 1000 expect(FactoryBot.build_stubbed(:post).id).to eq 1000 FactoryBot.build_stubbed_starting_id = 3000 expect(FactoryBot.build_stubbed(:post).id).to eq 3000 end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/define_child_before_parent_spec.rb
spec/acceptance/define_child_before_parent_spec.rb
describe "defining a child factory before a parent" do before do define_model("User", name: :string, admin: :boolean, email: :string, upper_email: :string, login: :string) FactoryBot.define do factory :admin, parent: :user do admin { true } end factory :user do name { "awesome" } end end end it "creates admin factories correctly" do expect(FactoryBot.create(:admin)).to be_admin end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/modify_inherited_spec.rb
spec/acceptance/modify_inherited_spec.rb
describe "modifying inherited factories with traits" do before do define_model("User", gender: :string, admin: :boolean, age: :integer) FactoryBot.define do factory :user do trait(:female) { gender { "Female" } } trait(:male) { gender { "Male" } } trait(:young_admin) do admin { true } age { 17 } end female young_admin factory :female_user do gender { "Female" } age { 25 } end factory :male_user do gender { "Male" } end end end end it "returns the correct value for overridden attributes from traits" do expect(FactoryBot.build(:male_user).gender).to eq "Male" end it "returns the correct value for overridden attributes from traits defining multiple attributes" do expect(FactoryBot.build(:female_user).gender).to eq "Female" expect(FactoryBot.build(:female_user).age).to eq 25 expect(FactoryBot.build(:female_user).admin).to eq true end it "allows modification of attributes created via traits" do FactoryBot.modify do factory :male_user do age { 20 } end end expect(FactoryBot.build(:male_user).gender).to eq "Male" expect(FactoryBot.build(:male_user).age).to eq 20 expect(FactoryBot.build(:male_user).admin).to eq true end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/definition_without_block_spec.rb
spec/acceptance/definition_without_block_spec.rb
describe "an instance generated by a factory" do before do define_model("User") FactoryBot.define do factory :user end end it "registers the user factory" do expect(FactoryBot::Internal.factory_by_name(:user)) .to be_a(FactoryBot::Factory) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/register_strategies_spec.rb
spec/acceptance/register_strategies_spec.rb
shared_context "registering custom strategies" do before do define_class("NamedObject") do attr_accessor :name end end let(:custom_strategy) do Class.new do def result(evaluation) evaluation.object.tap do |instance| instance.name = "Custom strategy" end end end end end describe "register custom strategies" do include_context "registering custom strategies" before do FactoryBot.define do factory :named_object do name { "Great" } end end end it "allows overriding default strategies" do expect(FactoryBot.build(:named_object).name).to eq "Great" FactoryBot.register_strategy(:build, custom_strategy) expect(FactoryBot.build(:named_object).name).to eq "Custom strategy" end it "allows adding additional strategies" do FactoryBot.register_strategy(:insert, custom_strategy) expect(FactoryBot.build(:named_object).name).to eq "Great" expect(FactoryBot.insert(:named_object).name).to eq "Custom strategy" end it "allows using the *_list method to build a list using a custom strategy" do FactoryBot.register_strategy(:insert, custom_strategy) inserted_items = FactoryBot.insert_list(:named_object, 2) 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 FactoryBot.register_strategy(:insert, custom_strategy) inserted_items = FactoryBot.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 FactoryBot::Syntax::Methods when custom strategies have been declared" do include FactoryBot::Syntax::Methods include_context "registering custom strategies" before do FactoryBot.define do factory :named_object do name { "Great" } end end end it "allows adding additional strategies" do FactoryBot.register_strategy(:insert, custom_strategy) expect(insert(:named_object).name).to eq "Custom strategy" end end describe "associations without overriding :strategy" do include_context "registering custom strategies" before do define_model("Post", user_id: :integer) do belongs_to :user end define_model("User", name: :string) FactoryBot.define do factory :post do user end factory :user do name { "John Doe" } end end end context "when the :use_parent_strategy config option is set to false" do it "uses the overridden strategy on the association" do FactoryBot.register_strategy(:create, custom_strategy) with_temporary_assignment(FactoryBot, :use_parent_strategy, false) do post = FactoryBot.build(:post) expect(post.user.name).to eq "Custom strategy" end end end context "when the :use_parent_strategy config option is set to true" do it "uses the parent strategy on the association" do FactoryBot.register_strategy(:create, custom_strategy) with_temporary_assignment(FactoryBot, :use_parent_strategy, true) do post = FactoryBot.build(:post) expect(post.user.name).to eq "John Doe" end end end end describe "associations overriding :strategy" do include_context "registering custom strategies" before do define_model("Post", user_id: :integer) do belongs_to :user end define_model("User", name: :string) FactoryBot.define do factory :post do association :user, strategy: :insert end factory :user do name { "John Doe" } end end end it "uses the overridden create strategy to create the association" do FactoryBot.register_strategy(:insert, custom_strategy) post = FactoryBot.build(:post) expect(post.user.name).to eq "Custom strategy" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attributes_ordered_spec.rb
spec/acceptance/attributes_ordered_spec.rb
describe "a generated attributes hash where order matters" do include FactoryBot::Syntax::Methods before do define_model("ParentModel", static: :integer, evaluates_first: :integer, evaluates_second: :integer, evaluates_third: :integer) FactoryBot.define do factory :parent_model do evaluates_first { static } evaluates_second { evaluates_first } evaluates_third { evaluates_second } factory :child_model do static { 1 } end end factory :without_parent, class: ParentModel do evaluates_first { static } evaluates_second { evaluates_first } evaluates_third { evaluates_second } static { 1 } end end end context "factory with a parent" do subject { FactoryBot.build(:child_model) } it "assigns attributes in the order they're defined" do expect(subject[:evaluates_first]).to eq 1 expect(subject[:evaluates_second]).to eq 1 expect(subject[:evaluates_third]).to eq 1 end end context "factory without a parent" do subject { FactoryBot.build(:without_parent) } it "assigns attributes in the order they're defined without a parent class" do expect(subject[:evaluates_first]).to eq 1 expect(subject[:evaluates_second]).to eq 1 expect(subject[:evaluates_third]).to eq 1 end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/acceptance/attribute_aliases_spec.rb
spec/acceptance/attribute_aliases_spec.rb
describe "attribute aliases" do around do |example| original_aliases = FactoryBot.aliases.dup example.run ensure FactoryBot.aliases.clear FactoryBot.aliases.concat(original_aliases) end describe "basic alias functionality" do it "allows using different parameter names that map to model attributes" do FactoryBot.aliases << [/author_name/, "name"] define_model("User", name: :string, author_name: :string) FactoryBot.define do factory :user do name { "Default Name" } end end user = FactoryBot.create(:user, author_name: "Custom Name") expect(user.author_name).to eq "Custom Name" expect(user.name).to be_nil end it "ignores factory defaults when alias is used" do FactoryBot.aliases << [/display_name/, "name"] define_model("User", name: :string, display_name: :string) FactoryBot.define do factory :user do name { "Factory Name" } end end user = FactoryBot.create(:user, display_name: "Override Name") expect(user.display_name).to eq "Override Name" expect(user.name).to be_nil end end describe "built-in _id aliases" do it "automatically alias between associations and foreign keys" do define_model("User", name: :string) define_model("Post", user_id: :integer) do belongs_to :user, optional: true end FactoryBot.define do factory :user do name { "Test User" } end factory :post end user = FactoryBot.create(:user) post_with_direct_id = FactoryBot.create(:post, user_id: user.id) expect(post_with_direct_id.user_id).to eq user.id post_with_association = FactoryBot.create(:post, user: user) expect(post_with_association.user_id).to eq user.id end it "prevents conflicts between associations and foreign keys" do define_model("User", name: :string, age: :integer) define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user do factory :user_with_name do name { "John Doe" } end end factory :post do user end end post_with_foreign_key = FactoryBot.build(:post, user_id: 1) expect(post_with_foreign_key.user_id).to eq 1 end it "allows passing attributes to associated factories" do define_model("User", name: :string, age: :integer) define_model("Post", user_id: :integer) do belongs_to :user end FactoryBot.define do factory :user do factory :user_with_name do name { "John Doe" } end end factory :post do user end factory :post_with_named_user, class: Post do user factory: :user_with_name, age: 20 end end created_user = FactoryBot.create(:post_with_named_user).user expect(created_user.name).to eq "John Doe" expect(created_user.age).to eq 20 end end describe "custom alias patterns" do it "supports regex patterns with capture groups" do FactoryBot.aliases << [/(.+)_alias/, '\1'] define_model("User", name: :string, name_alias: :string, email: :string, email_alias: :string) FactoryBot.define do factory :user do name { "Default Name" } email { "default@example.com" } end end user = FactoryBot.create(:user, name_alias: "Aliased Name", email_alias: "aliased@example.com") expect(user.name).to be_nil expect(user.email).to be_nil expect(user.name_alias).to eq "Aliased Name" expect(user.email_alias).to eq "aliased@example.com" end it "supports multiple alias patterns working together" do FactoryBot.aliases << [/primary_(.+)/, '\1'] FactoryBot.aliases << [/alt_name/, "name"] define_model("User", name: :string, email: :string, primary_email: :string, alt_name: :string) FactoryBot.define do factory :user do name { "Default Name" } email { "default@example.com" } end end user = FactoryBot.create(:user, primary_email: "primary@example.com", alt_name: "Alternative Name") expect(user.name).to be_nil expect(user.email).to be_nil expect(user.primary_email).to eq "primary@example.com" expect(user.alt_name).to eq "Alternative Name" end it "works with custom foreign key names" do FactoryBot.aliases << [/owner_id/, "user_id"] define_model("User", name: :string) define_model("Document", user_id: :integer, owner_id: :integer, title: :string) do belongs_to :user, optional: true end FactoryBot.define do factory :user do name { "Test User" } end factory :document do title { "Test Document" } end end document_owner = FactoryBot.create(:user) document = FactoryBot.create(:document, owner_id: document_owner.id) expect(document.user_id).to be_nil expect(document.owner_id).to eq document_owner.id expect(document.title).to eq "Test Document" end end describe "edge cases" do it "allows setting nil values through aliases" do FactoryBot.aliases << [/clear_name/, "name"] define_model("User", name: :string, clear_name: :string) FactoryBot.define do factory :user do name { "Default Name" } end end user = FactoryBot.create(:user, clear_name: nil) expect(user.name).to be_nil expect(user.clear_name).to be_nil end context "when both alias and target attributes exist on model" do it "ignores factory defaults for target when alias is used" do FactoryBot.aliases << [/one/, "two"] define_model("User", two: :string, one: :string) FactoryBot.define do factory :user do two { "set value" } end end user = FactoryBot.create(:user, one: "override") expect(user.one).to eq "override" expect(user.two).to be_nil end end end describe "with attributes_for strategy" do it "includes alias names in hash and ignores aliased factory defaults" do FactoryBot.aliases << [/author_name/, "name"] define_model("User", name: :string, author_name: :string) FactoryBot.define do factory :user do name { "Default Name" } end end attributes = FactoryBot.attributes_for(:user, author_name: "Custom Name") expect(attributes[:author_name]).to eq "Custom Name" expect(attributes[:name]).to be_nil end end describe "attribute conflicts with _id patterns" do it "doesn't set factory defaults when alias is used instead of target attribute" do define_model("User", name: :string, response_id: :integer) FactoryBot.define do factory :user do name { "orig name" } response_id { 42 } end end attributes = FactoryBot.attributes_for(:user, name: "new name", response: 13.75) expect(attributes[:name]).to eq "new name" expect(attributes[:response]).to eq 13.75 expect(attributes[:response_id]).to be_nil end it "allows setting both attribute and attribute_id without conflicts" do define_model("User", name: :string, response: :string, response_id: :float) FactoryBot.define do factory :user do name { "orig name" } response { "orig response" } response_id { 42 } end end user = FactoryBot.build(:user, name: "new name", response: "new response", response_id: 13.75) expect(user.name).to eq "new name" expect(user.response).to eq "new response" expect(user.response_id).to eq 13.75 end context "when association overrides trait foreign key" do before do define_model("User", name: :string) define_model("Post", user_id: :integer, title: :string) do belongs_to :user, optional: true end FactoryBot.define do factory :user do name { "Test User" } end factory :post do association :user title { "Test Post" } trait :with_system_user_id do user_id { 999 } end trait :with_user_id_100 do user_id { 100 } end trait :with_user_id_200 do user_id { 200 } end end end end it "prefers association override over trait foreign key" do user = FactoryBot.create(:user) post = FactoryBot.build(:post, :with_system_user_id, user: user) expect(post.user).to be user expect(post.user_id).to eq user.id end it "uses trait foreign key when no association override is provided" do post = FactoryBot.build(:post, :with_system_user_id) expect(post.user).to be nil expect(post.user_id).to eq 999 end it "handles multiple traits with foreign keys correctly" do user = FactoryBot.create(:user) post = FactoryBot.build(:post, :with_user_id_100, :with_user_id_200, user: user) expect(post.user).to be user expect(post.user_id).to eq user.id end end end context "when a factory defines attributes for both sides of an association" do before do define_model("User", name: :string, age: :integer) define_model("Post", user_id: :integer, title: :string) do belongs_to :user end end context "when using the build strategy" do it "prefers the :user association when defined after the :user_id attribute" do FactoryBot.define do factory :user factory :post do user_id { 999 } user end end user = FactoryBot.build_stubbed(:user) post = FactoryBot.build(:post, user_id: user.id) # A regression from v6.5.5 resulted in an extraneous user instance being # built and assigned to post.user; it also failed to use the user_id override expect(post.user).to be nil expect(post.user_id).to eq user.id end it "prefers the :user_id attribute when defined after the :user attribute" do FactoryBot.define do factory :user factory :post do user user_id { 999 } end end user = FactoryBot.build_stubbed(:user) post = FactoryBot.build(:post, user: user) # A regression from v6.5.5 erroneously assigns the value of 999 to post.user_id # and fails to assign the user override expect(post.user).to be user expect(post.user_id).to be user.id end end context "when using the create strategy" do it "handles an override of the foreign key when the :user association is declared last" do FactoryBot.define do factory :user factory :post do user_id { 999 } user end end user = FactoryBot.create(:user) post = FactoryBot.create(:post, user_id: user.id) # A regression in v6.5.5 created an erroneous second user and assigned # that to post.user and post.user_id. expect(post.user.id).to be user.id expect(post.user_id).to eq user.id expect(User.count).to eq 1 end it "handles an override of the associated object when the :user association is declared last" do FactoryBot.define do factory :user factory :post do user_id { 999 } user end end user = FactoryBot.create(:user) post = FactoryBot.create(:post, user: user) # This worked fine in v6.5.5, no regression behavior exhibited expect(post.user).to eq user expect(post.user_id).to eq user.id expect(User.count).to eq 1 end it "handles an override of the associated object when :user_id is declared last" do FactoryBot.define do factory :user factory :post do user # this :user_id attribute is purposely declared after :user user_id { 999 } end end user = FactoryBot.create(:user) post = FactoryBot.create(:post, user: user) # A regression from v6.5.5 erroneously asignes 999 to post.user_id # and leaves post.user assigned to nil expect(post.user_id).to eq user.id expect(post.user).to eq user expect(User.count).to eq 1 end it "handles an override of the foreign key when :user_id is declared last" do FactoryBot.define do factory :user do name { "tester" } age { 99 } end factory :post do user # this :user_id attribute is purposely declared after :user user_id { 999 } end end user = FactoryBot.create(:user) post = FactoryBot.create(:post, user_id: user.id) # A regression from v6.5.5 assigns the expected values to post.user and post.user_id # An erroneous second user instance, however, is created in the background expect(post.user_id).to eq user.id expect(post.user.id).to be user.id expect(User.count).to eq 1 end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/internal_spec.rb
spec/factory_bot/internal_spec.rb
describe FactoryBot::Internal do describe ".register_trait" do it "registers the provided trait" do trait = FactoryBot::Trait.new(:admin) configuration = FactoryBot::Internal.configuration expect { FactoryBot::Internal.register_trait(trait) } .to change { configuration.traits.count } .from(0) .to(1) end it "returns the registered trait" do trait = FactoryBot::Trait.new(:admin) expect(FactoryBot::Internal.register_trait(trait)).to eq trait end end describe ".trait_by_name" do it "finds a previously registered trait" do trait = FactoryBot::Trait.new(:admin) klass = instance_double("klass") FactoryBot::Internal.register_trait(trait) expect(trait.klass).to be_nil expect(FactoryBot::Internal.trait_by_name(trait.name, klass)).to eq trait expect(trait.klass).to eq klass end end describe ".register_sequence" do it "registers the provided sequence" do sequence = FactoryBot::Sequence.new(:email) configuration = FactoryBot::Internal.configuration expect { FactoryBot::Internal.register_sequence(sequence) } .to change { configuration.sequences.count } .from(0) .to(1) end it "returns the registered sequence" do sequence = FactoryBot::Sequence.new(:email) expect(FactoryBot::Internal.register_sequence(sequence)).to eq sequence end end describe ".sequence_by_name" do it "finds a registered sequence" do sequence = FactoryBot::Sequence.new(:email) FactoryBot::Internal.register_sequence(sequence) expect(FactoryBot::Internal.sequence_by_name(sequence.name)).to eq sequence end end describe ".rewind_sequences" do it "rewinds the sequences and the internal sequences" do sequence = instance_double(FactoryBot::Sequence, names: ["email"]) allow(sequence).to receive(:rewind) FactoryBot::Internal.register_sequence(sequence) inline_sequence = instance_double(FactoryBot::Sequence) allow(inline_sequence).to receive(:rewind) FactoryBot::Internal.register_inline_sequence(inline_sequence) FactoryBot::Internal.rewind_sequences expect(sequence).to have_received(:rewind).exactly(:once) expect(inline_sequence).to have_received(:rewind).exactly(:once) end end describe ".register_factory" do it "registers the provided factory" do factory = FactoryBot::Factory.new(:object) configuration = FactoryBot::Internal.configuration expect { FactoryBot::Internal.register_factory(factory) } .to change { configuration.factories.count } .from(0) .to(1) end it "returns the registered factory" do factory = FactoryBot::Factory.new(:object) expect(FactoryBot::Internal.register_factory(factory)).to eq factory end end describe ".factory_by_name" do it "finds a registered factory" do factory = FactoryBot::Factory.new(:object) FactoryBot::Internal.register_factory(factory) expect(FactoryBot::Internal.factory_by_name(factory.name)).to eq factory end end describe ".register_factory" do it "registers the provided factory" do factory = FactoryBot::Factory.new(:object) configuration = FactoryBot::Internal.configuration expect { FactoryBot::Internal.register_factory(factory) } .to change { configuration.factories.count } .from(0) .to(1) end it "returns the registered factory" do factory = FactoryBot::Factory.new(:object) expect(FactoryBot::Internal.register_factory(factory)).to eq factory end end describe ".factory_by_name" do it "finds a registered factory" do factory = FactoryBot::Factory.new(:object) FactoryBot::Internal.register_factory(factory) expect(FactoryBot::Internal.factory_by_name(factory.name)).to eq factory end end describe ".register_strategy" do it "register the provided strategy name with the class" do configuration = FactoryBot::Internal.configuration initial_strategies_count = configuration.strategies.count expect { FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class) }.to change { configuration.strategies.count } .from(initial_strategies_count) .to(initial_strategies_count + 1) end end describe ".strategy_by_name" do it "finds a registered strategy" do FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class) expect(FactoryBot::Internal.strategy_by_name(:strategy_name)) .to eq :strategy_class end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/null_factory_spec.rb
spec/factory_bot/null_factory_spec.rb
describe FactoryBot::NullFactory do it "delegates defined traits to its definition" do null_factory = FactoryBot::NullFactory.new expect(null_factory).to delegate(:defined_traits).to(:definition) end it "delegates callbacks to its definition" do null_factory = FactoryBot::NullFactory.new expect(null_factory).to delegate(:callbacks).to(:definition) end it "delegates attributes to its definition" do null_factory = FactoryBot::NullFactory.new expect(null_factory).to delegate(:attributes).to(:definition) end it "delegates constructor to its definition" do null_factory = FactoryBot::NullFactory.new expect(null_factory).to delegate(:constructor).to(:definition) end it "has a nil value for its compile attribute" do null_factory = FactoryBot::NullFactory.new expect(null_factory.compile).to be_nil end it "has a nil value for its class_name attribute" do null_factory = FactoryBot::NullFactory.new expect(null_factory.class_name).to be_nil end it "has an instance of FactoryBot::AttributeList for its attributes attribute" do null_factory = FactoryBot::NullFactory.new expect(null_factory.attributes).to be_an_instance_of(FactoryBot::AttributeList) end it "has FactoryBot::Evaluator as its evaluator class" do null_factory = FactoryBot::NullFactory.new expect(null_factory.evaluator_class).to eq FactoryBot::Evaluator end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/disallows_duplicates_registry_spec.rb
spec/factory_bot/disallows_duplicates_registry_spec.rb
describe FactoryBot::Decorator::DisallowsDuplicatesRegistry do it "delegates #register to the registry when not registered" do registry = double("registry", name: "Great thing", register: true) decorator = FactoryBot::Decorator::DisallowsDuplicatesRegistry.new(registry) allow(registry).to receive(:registered?).and_return false decorator.register(:awesome, {}) expect(registry).to have_received(:register).with(:awesome, {}) end it "raises when attempting to #register a previously registered strategy" do registry = double("registry", name: "Great thing", register: true) decorator = FactoryBot::Decorator::DisallowsDuplicatesRegistry.new(registry) allow(registry).to receive(:registered?).and_return true expect { decorator.register(:same_name, {}) } .to raise_error(FactoryBot::DuplicateDefinitionError, "Great thing already registered: same_name") end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/evaluator_class_definer_spec.rb
spec/factory_bot/evaluator_class_definer_spec.rb
describe FactoryBot::EvaluatorClassDefiner do it "returns an evaluator when accessing the evaluator class" do evaluator = define_evaluator(parent_class: FactoryBot::Evaluator) expect(evaluator).to be_a(FactoryBot::Evaluator) end it "adds each attribute to the evaluator" do attribute = stub_attribute(:attribute) { 1 } evaluator = define_evaluator(attributes: [attribute]) expect(evaluator.attribute).to eq 1 end it "evaluates the block in the context of the evaluator" do dependency_attribute = stub_attribute(:dependency) { 1 } attribute = stub_attribute(:attribute) { dependency + 1 } evaluator = define_evaluator(attributes: [dependency_attribute, attribute]) expect(evaluator.attribute).to eq 2 end it "only instance_execs the block once even when returning nil" do count = 0 attribute = stub_attribute(:attribute) { count += 1 nil } evaluator = define_evaluator(attributes: [attribute]) 2.times { evaluator.attribute } expect(count).to eq 1 end it "sets attributes on the evaluator class" do attributes = [stub_attribute, stub_attribute] evaluator = define_evaluator(attributes: attributes) expect(evaluator.attribute_lists).to eq [attributes] end context "with a custom evaluator as a parent class" do it "bases its attribute lists on itself and its parent evaluator" do parent_attributes = [stub_attribute, stub_attribute] parent_evaluator_class = define_evaluator_class(attributes: parent_attributes) child_attributes = [stub_attribute, stub_attribute] child_evaluator = define_evaluator( attributes: child_attributes, parent_class: parent_evaluator_class ) expect(child_evaluator.attribute_lists).to eq [parent_attributes, child_attributes] end end def define_evaluator(arguments = {}) evaluator_class = define_evaluator_class(arguments) evaluator_class.new(FactoryBot::Strategy::Null) end def define_evaluator_class(arguments = {}) evaluator_class_definer = FactoryBot::EvaluatorClassDefiner.new( arguments[:attributes] || [], arguments[:parent_class] || FactoryBot::Evaluator ) evaluator_class_definer.evaluator_class end def stub_attribute(name = :attribute, &value) value ||= -> {} double(name.to_s, name: name.to_sym, to_proc: value) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/declaration_list_spec.rb
spec/factory_bot/declaration_list_spec.rb
describe FactoryBot::DeclarationList, "#attributes" do it "returns an AttributeList" do declaration_list = FactoryBot::DeclarationList.new expect(declaration_list.attributes).to be_a(FactoryBot::AttributeList) end it "defines each attribute on the attribute list" do attribute1 = double("attribute 1") attribute2 = double("attribute 2") attribute3 = double("attribute 3") declaration1 = double("declaration 1", to_attributes: [attribute1, attribute2]) declaration2 = double("declaration2", to_attributes: [attribute3]) attribute_list = double("attribute list", define_attribute: true) declaration_list = FactoryBot::DeclarationList.new allow(FactoryBot::AttributeList).to receive(:new).and_return attribute_list declaration_list.declare_attribute(declaration1) declaration_list.declare_attribute(declaration2) declaration_list.attributes expect(attribute_list).to have_received(:define_attribute).with(attribute1) expect(attribute_list).to have_received(:define_attribute).with(attribute2) expect(attribute_list).to have_received(:define_attribute).with(attribute3) end end describe FactoryBot::DeclarationList, "#declare_attribute" do it "adds the declaration to the list when not overridable" do declaration1 = double("declaration", name: "declaration 1") declaration2 = double("declaration", name: "declaration 2") declaration_list = FactoryBot::DeclarationList.new declaration_list.declare_attribute(declaration1) expect(declaration_list.to_a).to eq [declaration1] declaration_list.declare_attribute(declaration2) expect(declaration_list.to_a).to eq [declaration1, declaration2] end it "adds the declaration to the list when overridable" do declaration1 = double("declaration", name: "declaration 1") declaration2 = double("declaration", name: "declaration 2") declaration_list = FactoryBot::DeclarationList.new declaration_list.overridable declaration_list.declare_attribute(declaration1) expect(declaration_list.to_a).to eq [declaration1] declaration_list.declare_attribute(declaration2) expect(declaration_list.to_a).to eq [declaration1, declaration2] end it "deletes declarations with the same name when overridable" do declaration1 = double("declaration", name: "declaration 1") declaration2 = double("declaration", name: "declaration 2") declaration_with_same_name = double("declaration", name: "declaration 1") declaration_list = FactoryBot::DeclarationList.new declaration_list.overridable declaration_list.declare_attribute(declaration1) expect(declaration_list.to_a).to eq [declaration1] declaration_list.declare_attribute(declaration2) expect(declaration_list.to_a).to eq [declaration1, declaration2] declaration_list.declare_attribute(declaration_with_same_name) expect(declaration_list.to_a).to eq [declaration2, declaration_with_same_name] end it "appends declarations with the same name when NOT overridable" do declaration1 = double("declaration", name: "declaration 1") declaration2 = double("declaration", name: "declaration 2") declaration_with_same_name = double("declaration", name: "declaration 1") # DeclarationList's `@overridable` attr is set to false by default declaration_list = FactoryBot::DeclarationList.new declaration_list.declare_attribute(declaration1) expect(declaration_list.to_a).to eq [declaration1] declaration_list.declare_attribute(declaration2) expect(declaration_list.to_a).to eq [declaration1, declaration2] declaration_list.declare_attribute(declaration_with_same_name) expect(declaration_list.to_a).to eq [declaration1, declaration2, declaration_with_same_name] end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/factory_spec.rb
spec/factory_bot/factory_spec.rb
describe FactoryBot::Factory do it "has a factory name" do name = :user factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) expect(factory.name).to eq name end it "has a build class" do name = :user klass = define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) expect(factory.build_class).to eq klass end it "returns associations" do define_class("Post") factory = FactoryBot::Factory.new(:post) FactoryBot::Internal.register_factory(FactoryBot::Factory.new(:admin)) factory.declare_attribute(FactoryBot::Declaration::Association.new(:author, {})) factory.declare_attribute(FactoryBot::Declaration::Association.new(:editor, {})) factory.declare_attribute(FactoryBot::Declaration::Implicit.new(:admin, factory)) factory.associations.each do |association| expect(association).to be_association end expect(factory.associations.to_a.length).to eq 3 end it "includes associations from the parent factory" do association_on_parent = FactoryBot::Declaration::Association.new(:association_on_parent, {}) association_on_child = FactoryBot::Declaration::Association.new(:association_on_child, {}) define_class("Post") factory = FactoryBot::Factory.new(:post) factory.declare_attribute(association_on_parent) FactoryBot::Internal.register_factory(factory) child_factory = FactoryBot::Factory.new(:child_post, parent: :post) child_factory.declare_attribute(association_on_child) expect(child_factory.associations.map(&:name)).to eq [:association_on_parent, :association_on_child] end describe "when overriding generated attributes with a hash" do it "returns the overridden value in the generated attributes" do name = :name value = "The price is right!" hash = {name => value} define_class("Name") factory = FactoryBot::Factory.new(name) declaration = FactoryBot::Declaration::Dynamic.new(name, false, -> { flunk }) factory.declare_attribute(declaration) result = factory.run(FactoryBot::Strategy::AttributesFor, hash) expect(result[name]).to eq value end it "overrides a symbol parameter with a string parameter" do name = :name define_class("Name") value = "The price is right!" factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) declaration = FactoryBot::Declaration::Dynamic.new(name, false, -> { flunk }) factory.declare_attribute(declaration) hash = {name.to_s => value} result = factory.run(FactoryBot::Strategy::AttributesFor, hash) expect(result[name]).to eq value end end describe "overriding an attribute with an alias" do it "uses the passed in value for the alias" do name = :user define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) attribute = FactoryBot::Declaration::Dynamic.new( :test, false, -> { "original" } ) factory.declare_attribute(attribute) FactoryBot.aliases << [/(.*)_alias/, '\1'] result = factory.run( FactoryBot::Strategy::AttributesFor, test_alias: "new" ) expect(result[:test_alias]).to eq "new" end it "discards the predefined value for the attribute" do name = :user define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) attribute = FactoryBot::Declaration::Dynamic.new( :test, false, -> { "original" } ) factory.declare_attribute(attribute) FactoryBot.aliases << [/(.*)_alias/, '\1'] result = factory.run( FactoryBot::Strategy::AttributesFor, test_alias: "new" ) expect(result[:test]).to be_nil end end it "guesses the build class from the factory name" do name = :user define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) expect(factory.build_class).to eq User end it "creates a new factory using the class of the parent" do name = :user define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) child = FactoryBot::Factory.new(:child, parent: factory.name) child.compile expect(child.build_class).to eq factory.build_class end it "creates a new factory while overriding the parent class" do name = :user define_class("User") factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) child = FactoryBot::Factory.new(:child, class: String, parent: factory.name) child.compile expect(child.build_class).to eq String end end describe FactoryBot::Factory, "when defined with a custom class" do it "is an instance of that custom class" do factory = FactoryBot::Factory.new(:author, class: Float) expect(factory.build_class).to eq Float end end describe FactoryBot::Factory, "when given a class that overrides #to_s" do it "sets build_class correctly" do define_class("Overriding") define_class("Overriding::Class") do def self.to_s "Overriding" end end overriding_class = Overriding::Class factory = FactoryBot::Factory.new(:overriding_class, class: Overriding::Class) expect(factory.build_class).to eq overriding_class end end describe FactoryBot::Factory, "when defined with a class instead of a name" do it "has a name" do klass = ArgumentError name = :argument_error factory = FactoryBot::Factory.new(klass) expect(factory.name).to eq name end it "has a build_class" do klass = ArgumentError factory = FactoryBot::Factory.new(klass) expect(factory.build_class).to eq klass end end describe FactoryBot::Factory, "when defined with a custom class name" do it "has a build_class equal to its custom class name" do factory = FactoryBot::Factory.new(:author, class: :argument_error) expect(factory.build_class).to eq ArgumentError end end describe FactoryBot::Factory, "with a name ending in s" do it "has a name" do factory = FactoryBot::Factory.new(:business) expect(factory.name).to eq :business end it "has a build class" do define_class("Business") factory = FactoryBot::Factory.new(:business) expect(factory.build_class).to eq Business end end describe FactoryBot::Factory, "with a string for a name" do it "has a name" do name = :string factory = FactoryBot::Factory.new(name.to_s) expect(factory.name).to eq name end it "sets build_class correctly with a class with an underscore" do name = :settings define_class("Admin_Settings_1") settings_class = Admin_Settings_1 factory = FactoryBot::Factory.new(name, class: "Admin_Settings_1") expect(factory.build_class).to eq settings_class end end describe FactoryBot::Factory, "for namespaced class" do it "sets build_class correctly with a namespaced class with Namespace::Class syntax" do name = :settings define_class("Admin") define_class("Admin::Settings") settings_class = Admin::Settings factory = FactoryBot::Factory.new(name, class: "Admin::Settings") expect(factory.build_class).to eq settings_class end it "sets build_class correctly with a namespaced class with namespace/class syntax" do name = :settings define_class("Admin") define_class("Admin::Settings") settings_class = Admin::Settings factory = FactoryBot::Factory.new(name, class: "admin/settings") expect(factory.build_class).to eq settings_class end end describe FactoryBot::Factory, "human names" do it "parses names without underscores" do factory = FactoryBot::Factory.new(:user) expect(factory.names).to eq [:user] end it "parses human names without underscores" do factory = FactoryBot::Factory.new(:user) expect(factory.human_names).to eq ["user"] end it "parses names with underscores" do factory = FactoryBot::Factory.new(:happy_user) expect(factory.names).to eq [:happy_user] end it "parses human names with underscores" do factory = FactoryBot::Factory.new(:happy_user) expect(factory.human_names).to eq ["happy user"] end it "parses names with big letters" do factory = FactoryBot::Factory.new(:LoL) expect(factory.names).to eq [:LoL] end it "parses human names with big letters" do factory = FactoryBot::Factory.new(:LoL) expect(factory.human_names).to eq ["lol"] end it "parses names with aliases" do factory = FactoryBot::Factory.new(:happy_user, aliases: [:gleeful_user, :person]) expect(factory.names).to eq [:happy_user, :gleeful_user, :person] end it "parses human names with aliases" do factory = FactoryBot::Factory.new(:happy_user, aliases: [:gleeful_user, :person]) expect(factory.human_names).to eq ["happy user", "gleeful user", "person"] end end describe FactoryBot::Factory, "running a factory" do def build_factory attribute = FactoryBot::Attribute::Dynamic.new(:name, false, -> { "value" }) attributes = [attribute] declaration = FactoryBot::Declaration::Dynamic.new(:name, false, -> { "value" }) strategy = double("strategy", result: "result") define_model("User", name: :string) allow(FactoryBot::Declaration::Dynamic).to receive(:new) .and_return declaration allow(declaration).to receive(:to_attributes).and_return attributes allow(FactoryBot::Strategy::Build).to receive(:new).and_return strategy factory = FactoryBot::Factory.new(:user) factory.declare_attribute(declaration) factory end it "creates the right strategy using the build class when running" do factory = build_factory factory.run(FactoryBot::Strategy::Build, {}) expect(FactoryBot::Strategy::Build).to have_received(:new).once end it "returns the result from the strategy when running" do factory = build_factory expect(factory.run(FactoryBot::Strategy::Build, {})).to eq "result" end it "calls the block and returns the result" do factory = build_factory block_run = nil block = ->(_result) { block_run = "changed" } factory.run(FactoryBot::Strategy::Build, {}, &block) expect(block_run).to eq "changed" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/definition_proxy_spec.rb
spec/factory_bot/definition_proxy_spec.rb
describe FactoryBot::DefinitionProxy, "#add_attribute" do it "declares a dynamic attribute on the factory when the proxy respects attributes" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) attribute_value = -> { "dynamic attribute" } proxy.add_attribute(:attribute_name, &attribute_value) expect(definition).to have_dynamic_declaration(:attribute_name) .with_value(attribute_value) end it "declares a dynamic attribute on the factory when the proxy ignores attributes" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition, true) attribute_value = -> { "dynamic attribute" } proxy.add_attribute(:attribute_name, &attribute_value) expect(definition).to have_dynamic_declaration(:attribute_name) .ignored .with_value(attribute_value) end end describe FactoryBot::DefinitionProxy, "#transient" do it "makes all attributes added ignored" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) attribute_value = -> { "dynamic_attribute" } proxy.transient do add_attribute(:attribute_name, &attribute_value) end expect(definition).to have_dynamic_declaration(:attribute_name) .ignored .with_value(attribute_value) end end describe FactoryBot::DefinitionProxy, "#method_missing" do it "declares an implicit declaration when called without args or a block" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.bogus expect(definition).to have_implicit_declaration(:bogus).with_factory(definition) end it "declares an association when called with a ':factory' key" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.author factory: :user expect(definition).to have_association_declaration(:author) .with_options(factory: :user) end it "declares a dynamic attribute when called with a block" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) attribute_value = -> { "dynamic attribute" } proxy.attribute_name(&attribute_value) expect(definition).to have_dynamic_declaration(:attribute_name) .with_value(attribute_value) end it "raises a NoMethodError when called with a static-attribute-like argument" do definition = FactoryBot::Definition.new(:broken) proxy = FactoryBot::DefinitionProxy.new(definition) invalid_call = -> { proxy.static_attributes_are_gone "true" } expect(&invalid_call).to raise_error( NoMethodError, /'static_attributes_are_gone'.*'broken' factory.*Did you mean\? 'static_attributes_are_gone \{ "true" \}'/m ) end end describe FactoryBot::DefinitionProxy, "#sequence" do def build_proxy(factory_name) definition = FactoryBot::Definition.new(factory_name) FactoryBot::DefinitionProxy.new(definition) end it "creates a new sequence starting at 1" do allow(FactoryBot::Sequence).to receive(:new).and_call_original proxy = build_proxy(:factory) proxy.sequence(:sequence) expect(FactoryBot::Sequence).to have_received(:new).with(:sequence, {uri_paths: []}) end it "creates a new sequence with an overridden starting value" do allow(FactoryBot::Sequence).to receive(:new).and_call_original proxy = build_proxy(:factory) override = "override" proxy.sequence(:sequence, override) expect(FactoryBot::Sequence).to have_received(:new) .with(:sequence, override, {uri_paths: []}) end it "creates a new sequence with a block" do allow(FactoryBot::Sequence).to receive(:new).and_call_original sequence_block = proc { |n| "user+#{n}@example.com" } proxy = build_proxy(:factory) proxy.sequence(:sequence, 1, &sequence_block) expect(FactoryBot::Sequence).to have_received(:new) .with(:sequence, 1, {uri_paths: []}, &sequence_block) end end describe FactoryBot::DefinitionProxy, "#association" do it "declares an association" do definition = FactoryBot::Definition.new(:definition_name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.association(:association_name) expect(definition).to have_association_declaration(:association_name) end it "declares an association with options" do definition = FactoryBot::Definition.new(:definition_name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.association(:association_name, name: "Awesome") expect(definition).to have_association_declaration(:association_name) .with_options(name: "Awesome") end it "when passing a block raises an error" do definition = FactoryBot::Definition.new(:post) proxy = FactoryBot::DefinitionProxy.new(definition) expect { proxy.association(:author) {} } .to raise_error( FactoryBot::AssociationDefinitionError, "Unexpected block passed to 'author' association in 'post' factory" ) end end describe FactoryBot::DefinitionProxy, "adding callbacks" do it "adding a :before_all callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.before(:all, &callback) expect(definition).to have_callback(:before_all).with_block(callback) end it "adding an :after_all callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.after(:all, &callback) expect(definition).to have_callback(:after_all).with_block(callback) end it "adding an :after_build callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.after(:build, &callback) expect(definition).to have_callback(:after_build).with_block(callback) end it "adding an :after_create callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.after(:create, &callback) expect(definition).to have_callback(:after_create).with_block(callback) end it "adding an :after_stub callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.after(:stub, &callback) expect(definition).to have_callback(:after_stub).with_block(callback) end it "adding both an :after_stub and an :after_create callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.after(:stub, :create, &callback) expect(definition).to have_callback(:after_stub).with_block(callback) expect(definition).to have_callback(:after_create).with_block(callback) end it "adding both a :before_stub and a :before_create callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.before(:stub, :create, &callback) expect(definition).to have_callback(:before_stub).with_block(callback) expect(definition).to have_callback(:before_create).with_block(callback) end it "adding both an :after_stub and a :before_create callback succeeds" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) callback = -> { "my awesome callback!" } proxy.callback(:after_stub, :before_create, &callback) expect(definition).to have_callback(:after_stub).with_block(callback) expect(definition).to have_callback(:before_create).with_block(callback) end end describe FactoryBot::DefinitionProxy, "#to_create" do it "accepts a block to run in place of #save!" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) to_create_block = ->(record) { record.persist } proxy.to_create(&to_create_block) expect(definition.to_create).to eq to_create_block end end describe FactoryBot::DefinitionProxy, "#factory" do it "without options" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.factory(:child) expect(proxy.child_factories).to include([:child, {}, nil]) end it "with options" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) proxy.factory(:child, awesome: true) expect(proxy.child_factories).to include([:child, {awesome: true}, nil]) end it "with a block" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) child_block = -> {} proxy.factory(:child, {}, &child_block) expect(proxy.child_factories).to include([:child, {}, child_block]) end end describe FactoryBot::DefinitionProxy, "#trait" do it "declares a trait" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) male_trait = proc { gender { "Male" } } proxy.trait(:male, &male_trait) expect(definition).to have_trait(:male).with_block(male_trait) end end describe FactoryBot::DefinitionProxy, "#initialize_with" do it "defines the constructor on the definition" do definition = FactoryBot::Definition.new(:name) proxy = FactoryBot::DefinitionProxy.new(definition) constructor = proc { [] } proxy.initialize_with(&constructor) expect(definition.constructor).to eq constructor end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/strategy_spec.rb
spec/factory_bot/strategy_spec.rb
describe FactoryBot::Strategy do it "returns the class passed when it is instantiated with a class" do strategy = define_class("MyAwesomeClass") result = described_class.lookup_strategy(strategy) expect(result).to eq strategy end it "finds the strategy by name when instantiated with a symbol" do strategy = define_class("MyAwesomeClass") allow(FactoryBot::Internal).to receive(:strategy_by_name).and_return(strategy) described_class.lookup_strategy(:build) expect(FactoryBot::Internal).to have_received(:strategy_by_name).with(:build) end it "returns the strategy found when instantiated with a symbol" do strategy = define_class("MyAwesomeClass") allow(FactoryBot::Internal).to receive(:strategy_by_name).and_return(strategy) result = described_class.lookup_strategy(:build) expect(result).to eq strategy end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute_spec.rb
spec/factory_bot/attribute_spec.rb
describe FactoryBot::Attribute do it "converts the name attribute to a symbol" do name = "user" attribute = FactoryBot::Attribute.new(name, false) expect(attribute.name).to eq name.to_sym end it "is not an association" do name = "user" attribute = FactoryBot::Attribute.new(name, false) expect(attribute).not_to be_association end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/definition_spec.rb
spec/factory_bot/definition_spec.rb
describe FactoryBot::Definition do it "delegates :declare_attribute to declarations" do definition = described_class.new(:name) expect(definition).to delegate(:declare_attribute).to(:declarations) end it "creates a new attribute list with the name passed when given a name" do name = "great name" allow(FactoryBot::DeclarationList).to receive(:new) FactoryBot::Definition.new(name) expect(FactoryBot::DeclarationList).to have_received(:new).with(name) end it "has a name" do name = "factory name" definition = described_class.new(name) expect(definition.name).to eq(name) end it "has an overridable declaration list" do list = double("declaration list", overridable: true) allow(FactoryBot::DeclarationList).to receive(:new).and_return list definition = described_class.new(:name) expect(definition.overridable).to eq definition expect(list).to have_received(:overridable).once end it "maintains a list of traits" do trait1 = double(:trait) trait2 = double(:trait) definition = described_class.new(:name) definition.define_trait(trait1) definition.define_trait(trait2) expect(definition.defined_traits).to include(trait1, trait2) end it "adds only unique traits" do trait1 = double(:trait) definition = described_class.new(:name) definition.define_trait(trait1) definition.define_trait(trait1) expect(definition.defined_traits.size).to eq 1 end it "maintains a list of callbacks" do callback1 = "callback1" callback2 = "callback2" definition = described_class.new(:name) definition.add_callback(callback1) definition.add_callback(callback2) expect(definition.callbacks).to eq [callback1, callback2] end it "doesn't expose a separate create strategy when none is specified" do definition = described_class.new(:name) expect(definition.to_create).to be_nil end it "exposes a non-default create strategy when one is provided by the user" do definition = described_class.new(:name) block = proc {} definition.to_create(&block) expect(definition.to_create).to eq block end it "maintains a list of enum fields" do definition = described_class.new(:name) enum_field = double("enum_field") definition.register_enum(enum_field) expect(definition.registered_enums).to include(enum_field) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/sequence_spec.rb
spec/factory_bot/sequence_spec.rb
shared_examples "a sequence" do |options| first_value = options[:first_value] second_value = options[:second_value] it "has a next value equal to its first value" do expect(subject.next).to eq first_value end it "has a next value equal to the 2nd value after being incremented" do subject.next expect(subject.next).to eq second_value end it "has a next value equal to the 1st value after rewinding" do subject.next subject.rewind expect(subject.next).to eq first_value end end describe FactoryBot::Sequence do describe ".find" do before(:each) do define_class("User") { attr_accessor :name } FactoryBot.define do factory :user do trait :with_email do sequence(:email) { |n| "user_#{n}@example.com" } end end end end it "accepts a list of symbols" do expect(described_class.find(:user, :with_email, :email)).to be_truthy end it "accepts a list of strings" do expect(described_class.find("user", "with_email", "email")).to be_truthy end it "accepts a mixture of symbols & strings" do expect(described_class.find(:user, "with_email", :email)).to be_truthy end it "returns nil with a non-matching URI" do expect(described_class.find(:user, :email)).to be_nil end it "raises an exception with no arguments given" do expect { described_class.find } .to raise_error ArgumentError, /wrong number of arguments, expected 1\+/ end end describe ".find_by_uri" do before(:each) do define_class("User") { attr_accessor :name } FactoryBot.define do factory :user do trait :with_email do sequence(:email) { |n| "user_#{n}@example.com" } end end end end it "accepts a String" do expect(described_class.find_by_uri("user/with_email/email")).to be_truthy end it "accepts a Symbol" do expect(described_class.find_by_uri(:"user/with_email/email")).to be_truthy end it "returns nil with a non-matching URI" do expect(described_class.find_by_uri("user/email")).to be_nil end it "raises an exception with no arguments given" do expect { described_class.find_by_uri } .to raise_error ArgumentError, /wrong number of arguments \(given 0, expected 1\)/ end end describe "a basic sequence" do let(:name) { :test } subject { FactoryBot::Sequence.new(name) { |n| "=#{n}" } } its(:name) { should eq name } its(:names) { should eq [name] } it_behaves_like "a sequence", first_value: "=1", second_value: "=2" end describe "a custom sequence" do subject { FactoryBot::Sequence.new(:name, "A") { |n| "=#{n}" } } it_behaves_like "a sequence", first_value: "=A", second_value: "=B" end describe "a sequence with aliases using default value" do subject do FactoryBot::Sequence.new(:test, aliases: [:alias, :other]) do |n| "=#{n}" end end it "has the expected names as its names" do names = [:foo, :bar, :baz] sequence = FactoryBot::Sequence.new(names.first, aliases: names.last(2)) { "=#{n}" } expect(sequence.names).to eq names end it_behaves_like "a sequence", first_value: "=1", second_value: "=2" end describe "a sequence with custom value and aliases" do subject do FactoryBot::Sequence.new(:test, 3, aliases: [:alias, :other]) do |n| "=#{n}" end end it "has the expected names as its names" do names = [:foo, :bar, :baz] sequence = FactoryBot::Sequence.new(names.first, 3, aliases: names.last(2)) { "=#{n}" } expect(sequence.names).to eq names end it_behaves_like "a sequence", first_value: "=3", second_value: "=4" end describe "a basic sequence without a block" do subject { FactoryBot::Sequence.new(:name) } it_behaves_like "a sequence", first_value: 1, second_value: 2 end describe "a custom sequence without a block" do subject { FactoryBot::Sequence.new(:name, "A") } it_behaves_like "a sequence", first_value: "A", second_value: "B" end describe "a sequence with lazy initial value and a block" do subject do FactoryBot::Sequence.new(:test, proc { "J" }) do |n| "=#{n}" end end it_behaves_like "a sequence", first_value: "=J", second_value: "=K" end describe "a sequence with a lazy initial value without a block" do subject do FactoryBot::Sequence.new(:test, proc { 3 }) end it_behaves_like "a sequence", first_value: 3, second_value: 4 end describe "iterating over items in an enumerator" do subject do FactoryBot::Sequence.new(:name, %w[foo bar].to_enum) { |n| "=#{n}" } end it "navigates to the next items until no items remain" do sequence = FactoryBot::Sequence.new(:name, %w[foo bar].to_enum) { |n| "=#{n}" } expect(sequence.next).to eq "=foo" expect(sequence.next).to eq "=bar" expect { sequence.next }.to raise_error(StopIteration) end it_behaves_like "a sequence", first_value: "=foo", second_value: "=bar" end it "a custom sequence and scope increments within the correct scope" do sequence = FactoryBot::Sequence.new(:name, "A") { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") expect(sequence.next(scope)).to eq "=Aattribute" end it "a custom lazy sequence and scope increments within the correct scope" do sequence = FactoryBot::Sequence.new(:name, proc { "A" }) { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") expect(sequence.next(scope)).to eq "=Aattribute" expect(sequence.next(scope)).to eq "=Battribute" end it "a custom sequence and scope increments within the correct scope when incrementing" do sequence = FactoryBot::Sequence.new(:name, "A") { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") sequence.next(scope) expect(sequence.next(scope)).to eq "=Battribute" end it "a custom lazy sequence and scope increments within the correct scope when incrementing" do sequence = FactoryBot::Sequence.new(:name, proc { "A" }) { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") sequence.next(scope) expect(sequence.next(scope)).to eq "=Battribute" end it "a custom scope increments within the correct scope after rewinding" do sequence = FactoryBot::Sequence.new(:name, "A") { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") sequence.next(scope) sequence.rewind expect(sequence.next(scope)).to eq "=Aattribute" end it "a custom scope with a lazy sequence increments within the correct scope after rewinding" do sequence = FactoryBot::Sequence.new(:name, proc { "A" }) { |n| "=#{n}#{foo}" } scope = double("scope", foo: "attribute") sequence.next(scope) sequence.rewind expect(sequence.next(scope)).to eq "=Aattribute" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute_assignment_spec.rb
spec/factory_bot/attribute_assignment_spec.rb
describe "Attribute Assignment" do it "sets the <attribute> default value if not overridden" do name = :user define_class("User") { attr_accessor :name, :response } factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) attr_1 = FactoryBot::Declaration::Dynamic.new(:name, false, -> { "orig name" }) attr_2 = FactoryBot::Declaration::Dynamic.new(:response, false, -> { "orig response" }) factory.declare_attribute(attr_1) factory.declare_attribute(attr_2) user = factory.run(FactoryBot::Strategy::Build, {}) expect(user.name).to eq "orig name" expect(user.response).to eq "orig response" end it "sets the <attribute> when directly named" do name = :user define_class("User") { attr_accessor :name, :response } factory = FactoryBot::Factory.new(name) FactoryBot::Internal.register_factory(factory) attr_1 = FactoryBot::Declaration::Dynamic.new(:name, false, -> { "orig name" }) attr_2 = FactoryBot::Declaration::Dynamic.new(:response, false, -> { "orig response" }) factory.declare_attribute(attr_1) factory.declare_attribute(attr_2) user = factory.run( FactoryBot::Strategy::Build, name: "new name", response: "new response" ) expect(user.name).to eq "new name" expect(user.response).to eq "new response" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/aliases_spec.rb
spec/factory_bot/aliases_spec.rb
describe FactoryBot, "aliases" do it "for an attribute should include the original attribute and a version suffixed with '_id'" do aliases = FactoryBot.aliases_for(:test) expect(aliases).to include(:test, :test_id) end it "for a foreign key should include both the suffixed and un-suffixed variants" do aliases = FactoryBot.aliases_for(:test_id) expect(aliases).to include(:test, :test_id) end it "for an attribute which starts with an underscore should not include a non-underscored version" do aliases = FactoryBot.aliases_for(:_id) expect(aliases).not_to include(:id) end end describe FactoryBot, "after defining an alias" do it "the list of aliases should include a variant with no suffix at all, and one with an '_id' suffix" do FactoryBot.aliases << [/(.*)_suffix/, '\1'] aliases = FactoryBot.aliases_for(:test_suffix) expect(aliases).to include(:test, :test_suffix_id) end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/registry_spec.rb
spec/factory_bot/registry_spec.rb
describe FactoryBot::Registry do it "is an enumerable" do registry = FactoryBot::Registry.new("Great thing") expect(registry).to be_kind_of(Enumerable) end it "finds a registered object" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:object_name, registered_object) expect(registry.find(:object_name)).to eq registered_object end it "finds a registered object with square brackets" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:object_name, registered_object) expect(registry[:object_name]).to eq registered_object end it "raises when an object cannot be found" do registry = FactoryBot::Registry.new("Great thing") expect { registry.find(:object_name) } .to raise_error(KeyError, "Great thing not registered: \"object_name\"") end it "includes a did_you_mean message" do registry = FactoryBot::Registry.new(:registry) registered_object = double(:registered_object) registry.register(:factory_bot, registered_object) expect { registry.find(:factory_bit) }.to raise_did_you_mean_error end it "adds and returns the object registered" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") expect(registry.register(:object_name, registered_object)).to eq registered_object end it "knows that an object is registered by symbol" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:object_name, registered_object) expect(registry).to be_registered(:object_name) end it "knows that an object is registered by string" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:object_name, registered_object) expect(registry).to be_registered("object_name") end it "knows when an object is not registered" do registry = FactoryBot::Registry.new("Great thing") expect(registry).not_to be_registered("bogus") end it "iterates registered objects" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") second_registered_object = double("second registered object") registry.register(:first_object, registered_object) registry.register(:second_object, second_registered_object) expect(registry.to_a).to eq [registered_object, second_registered_object] end it "does not include duplicate objects with registered under different names" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:first_object, registered_object) registry.register(:second_object, registered_object) expect(registry.to_a).to eq [registered_object] end it "clears registered factories" do registry = FactoryBot::Registry.new("Great thing") registered_object = double("registered object") registry.register(:object_name, registered_object) registry.clear expect(registry.count).to be_zero end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/callback_spec.rb
spec/factory_bot/callback_spec.rb
describe FactoryBot::Callback do it "has a name" do expect(FactoryBot::Callback.new(:after_create, -> {}).name).to eq :after_create end it "converts strings to symbols" do expect(FactoryBot::Callback.new("after_create", -> {}).name).to eq :after_create end it "runs its block with no parameters" do ran_with = nil FactoryBot::Callback.new(:after_create, -> { ran_with = [] }).run(:one, :two) expect(ran_with).to eq [] end it "runs its block with one parameter" do ran_with = nil FactoryBot::Callback.new(:after_create, ->(one) { ran_with = [one] }).run(:one, :two) expect(ran_with).to eq [:one] end it "runs its block with two parameters" do ran_with = nil FactoryBot::Callback.new(:after_create, ->(one, two) { ran_with = [one, two] }).run(:one, :two) expect(ran_with).to eq [:one, :two] end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/uri_manager_spec.rb
spec/factory_bot/uri_manager_spec.rb
describe FactoryBot::UriManager do describe ".build_uri" do it "combines the parts to form a Symbol" do expect(described_class.build_uri(:ep1, :ep2, :ep3)) .to eq :"ep1/ep2/ep3" end it "works with a single part" do expect(described_class.build_uri(:ep1)) .to eq :ep1 end it "works with multiple arrays of parts" do expect(described_class.build_uri(%i[ep1 ep2], %i[ep3 ep4])) .to eq :"ep1/ep2/ep3/ep4" end it "returns nil when no parts provided" do expect(described_class.build_uri).to be_nil end it "removes leading and trailing slashes" do expect(described_class.build_uri("/start", "end/")) .to eq :"start/end" end it "converts space to underlines" do expect(described_class.build_uri("starting now", "the end is nigh")) .to eq :"starting___now/the_end_is_____nigh" end end describe "#initialize" do context "when only endpoints are provided" do it "creates one URI for each endpoint" do uri_manager = FactoryBot::UriManager.new(:ep1, :ep2, :ep3) expect(uri_manager.uri_list).to eq %i[ep1 ep2 ep3] end it "each URI is a Symbol" do uri_manager = FactoryBot::UriManager.new("ep1", "ep2", "ep3") expect(uri_manager.uri_list).to eq %i[ep1 ep2 ep3] end it "accepts a combination of Symbols & Strings" do uri_manager = FactoryBot::UriManager.new(:ep1, "ep2", :ep3) expect(uri_manager.uri_list).to eq %i[ep1 ep2 ep3] end it "replaces spaces with underlines" do uri_manager = FactoryBot::UriManager.new("ep 1", "e p 2", :ep3) expect(uri_manager.uri_list).to eq %i[ep_1 e_p_2 ep3] end it "stringifies endpoints with non-symbol characters" do uri_manager = FactoryBot::UriManager.new("ep @ 1", "e + 2") expect(uri_manager.uri_list).to eq %i[ep_@_1 e_+_2] end it "accepts a single endpoint" do uri_manager = FactoryBot::UriManager.new(:ep1) expect(uri_manager.uri_list).to eq [:ep1] end it "accepts an array of endpoints" do uri_manager = FactoryBot::UriManager.new([:ep1, "ep2", :ep3]) expect(uri_manager.uri_list).to eq %i[ep1 ep2 ep3] end it "fails with no endpoints given" do expect { FactoryBot::UriManager.new } .to raise_error ArgumentError, /wrong number of arguments \(given 0, expected 1\+\)/ end end context "when paths are also provided" do it "creates one URI for each path/endpoint combination" do uri_manager = FactoryBot::UriManager.new(:e1, :e2, paths: %i[p1 p2]) expect(uri_manager.uri_list).to eq %i[p1/e1 p2/e1 p1/e2 p2/e2] end it "accepts a combination of Symbol & String paths" do uri_manager = FactoryBot::UriManager.new(:e1, "e2", paths: [:p1, "path"]) expect(uri_manager.uri_list).to eq %i[p1/e1 path/e1 p1/e2 path/e2] end it "replaces spaces with underlines" do uri_manager = FactoryBot::UriManager.new(:e1, paths: ["path 1", "path 2"]) expect(uri_manager.uri_list).to eq %i[path_1/e1 path_2/e1] end it "accepts a single path" do uri_manager = FactoryBot::UriManager.new(:e1, :e2, paths: :test_path) expect(uri_manager.uri_list).to eq %i[test_path/e1 test_path/e2] end it "accepts an array of arrays of paths" do uri_manager = FactoryBot::UriManager.new(:e1, paths: [%i[p1 p2], [:p3]]) expect(uri_manager.uri_list).to eq %i[p1/e1 p2/e1 p3/e1] end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/find_definitions_spec.rb
spec/factory_bot/find_definitions_spec.rb
require "fileutils" shared_examples_for "finds definitions" do before do allow(FactoryBot).to receive(:load) FactoryBot.find_definitions end subject { FactoryBot } end RSpec::Matchers.define :load_definitions_from do |file| match do |given| @has_received = have_received(:load).with(File.expand_path(file)) @has_received.matches?(given) end description do "load definitions from #{file}" end failure_message do @has_received.failure_message end end describe "definition loading" do def self.in_directory_with_files(*files) before do @pwd = Dir.pwd @tmp_dir = File.join(File.dirname(__FILE__), "tmp") FileUtils.mkdir_p @tmp_dir Dir.chdir(@tmp_dir) files.each do |file| FileUtils.mkdir_p File.dirname(file) FileUtils.touch file end end after do Dir.chdir(@pwd) FileUtils.rm_rf(@tmp_dir) end end describe "with factories.rb" do in_directory_with_files "factories.rb" it_should_behave_like "finds definitions" do it { should load_definitions_from("factories.rb") } end end %w[spec test].each do |dir| describe "with a factories file under #{dir}" do in_directory_with_files File.join(dir, "factories.rb") it_should_behave_like "finds definitions" do it { should load_definitions_from("#{dir}/factories.rb") } end end describe "with a factories file under #{dir}/factories" do in_directory_with_files File.join(dir, "factories", "post_factory.rb") it_should_behave_like "finds definitions" do it { should load_definitions_from("#{dir}/factories/post_factory.rb") } end end describe "with several factories files under #{dir}/factories" do in_directory_with_files File.join(dir, "factories", "post_factory.rb"), File.join(dir, "factories", "person_factory.rb") it_should_behave_like "finds definitions" do it { should load_definitions_from("#{dir}/factories/post_factory.rb") } it { should load_definitions_from("#{dir}/factories/person_factory.rb") } end end describe "with several factories files under #{dir}/factories in non-alphabetical order" do in_directory_with_files File.join(dir, "factories", "b.rb"), File.join(dir, "factories", "a.rb") it "loads the files in the right order" do allow(FactoryBot).to receive(:load) wd = File.dirname(__FILE__) file_b = File.join(wd, "tmp", dir, "factories", "b.rb") file_a = File.join(wd, "tmp", dir, "factories", "a.rb") FactoryBot.find_definitions expect(FactoryBot).to have_received(:load).with(file_a).ordered expect(FactoryBot).to have_received(:load).with(file_b).ordered end end describe "with nested and unnested factories files under #{dir}" do in_directory_with_files File.join(dir, "factories.rb"), File.join(dir, "factories", "post_factory.rb"), File.join(dir, "factories", "person_factory.rb") it_should_behave_like "finds definitions" do it { should load_definitions_from("#{dir}/factories.rb") } it { should load_definitions_from("#{dir}/factories/post_factory.rb") } it { should load_definitions_from("#{dir}/factories/person_factory.rb") } end end describe "with deeply nested factory files under #{dir}" do in_directory_with_files File.join(dir, "factories", "subdirectory", "post_factory.rb"), File.join(dir, "factories", "subdirectory", "person_factory.rb") it_should_behave_like "finds definitions" do it { should load_definitions_from("#{dir}/factories/subdirectory/post_factory.rb") } it { should load_definitions_from("#{dir}/factories/subdirectory/person_factory.rb") } end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/null_object_spec.rb
spec/factory_bot/null_object_spec.rb
describe FactoryBot::NullObject do it "responds to the given methods" do methods_to_respond_to = %w[id age name admin?] null_object = FactoryBot::NullObject.new(methods_to_respond_to) methods_to_respond_to.each do |method_name| expect(null_object.__send__(method_name)).to be_nil expect(null_object).to respond_to(method_name) end end it "does not respond to other methods" do methods_to_respond_to = %w[id age name admin?] methods_to_not_respond_to = %w[email date_of_birth title] null_object = FactoryBot::NullObject.new(methods_to_respond_to) methods_to_not_respond_to.each do |method_name| expect { null_object.__send__(method_name) }.to raise_error(NoMethodError) expect(null_object).not_to respond_to(method_name) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute_list_spec.rb
spec/factory_bot/attribute_list_spec.rb
module AttributeList def build_attribute_list(*attributes) FactoryBot::AttributeList.new.tap do |list| attributes.each { |attribute| list.define_attribute(attribute) } end end end describe FactoryBot::AttributeList, "#define_attribute" do it "maintains a list of attributes" do attribute = double(:attribute, name: :attribute_name) another_attribute = double(:attribute, name: :another_attribute_name) list = FactoryBot::AttributeList.new list.define_attribute(attribute) expect(list.to_a).to eq [attribute] list.define_attribute(another_attribute) expect(list.to_a).to eq [attribute, another_attribute] end it "returns the attribute" do attribute = double(:attribute, name: :attribute_name) list = FactoryBot::AttributeList.new expect(list.define_attribute(attribute)).to eq attribute end it "raises if an attribute has already been defined" do attribute = double(:attribute, name: :attribute_name) list = FactoryBot::AttributeList.new expect { 2.times { list.define_attribute(attribute) } }.to raise_error( FactoryBot::AttributeDefinitionError, "Attribute already defined: attribute_name" ) end end describe FactoryBot::AttributeList, "#define_attribute with a named attribute list" do it "raises when the attribute is a self-referencing association" do association_with_same_name = FactoryBot::Attribute::Association.new(:author, :author, {}) list = FactoryBot::AttributeList.new(:author) expect { list.define_attribute(association_with_same_name) }.to raise_error( FactoryBot::AssociationDefinitionError, "Self-referencing association 'author' in 'author'" ) end it "does not raise when the attribute is not a self-referencing association" do association_with_different_name = FactoryBot::Attribute::Association.new(:author, :post, {}) list = FactoryBot::AttributeList.new expect { list.define_attribute(association_with_different_name) }.to_not raise_error end end describe FactoryBot::AttributeList, "#apply_attributes" do include AttributeList it "adds attributes in the order defined" do attribute1 = double(:attribute1, name: :attribute1) attribute2 = double(:attribute2, name: :attribute2) list = FactoryBot::AttributeList.new list.define_attribute(attribute1) list.apply_attributes(build_attribute_list(attribute2)) expect(list.to_a).to eq [attribute1, attribute2] end end describe FactoryBot::AttributeList, "#associations" do include AttributeList it "returns associations" do email_attribute = FactoryBot::Attribute::Dynamic.new( :email, false, ->(u) { "#{u.full_name}@example.com" } ) author_attribute = FactoryBot::Attribute::Association.new(:author, :user, {}) profile_attribute = FactoryBot::Attribute::Association.new(:profile, :profile, {}) list = build_attribute_list(email_attribute, author_attribute, profile_attribute) expect(list.associations.to_a).to eq [author_attribute, profile_attribute] end end describe FactoryBot::AttributeList, "filter based on ignored attributes" do include AttributeList def build_ignored_attribute(name) FactoryBot::Attribute::Dynamic.new(name, true, -> { "value" }) end def build_non_ignored_attribute(name) FactoryBot::Attribute::Dynamic.new(name, false, -> { "value" }) end it "filters #ignored attributes" do list = build_attribute_list( build_ignored_attribute(:comments_count), build_non_ignored_attribute(:email) ) expect(list.ignored.names).to eq [:comments_count] end it "filters #non_ignored attributes" do list = build_attribute_list( build_ignored_attribute(:comments_count), build_non_ignored_attribute(:email) ) expect(list.non_ignored.names).to eq [:email] end end describe FactoryBot::AttributeList, "generating names" do include AttributeList def build_ignored_attribute(name) FactoryBot::Attribute::Dynamic.new(name, true, -> { "value" }) end def build_non_ignored_attribute(name) FactoryBot::Attribute::Dynamic.new(name, false, -> { "value" }) end def build_association(name) FactoryBot::Attribute::Association.new(name, :user, {}) end it "knows all its #names" do list = build_attribute_list( build_ignored_attribute(:comments_count), build_non_ignored_attribute(:last_name), build_association(:avatar) ) expect(list.names).to eq [:comments_count, :last_name, :avatar] end it "knows all its #names for #ignored attributes" do list = build_attribute_list( build_ignored_attribute(:posts_count), build_non_ignored_attribute(:last_name), build_association(:avatar) ) expect(list.ignored.names).to eq [:posts_count] end it "knows all its #names for #non_ignored attributes" do list = build_attribute_list( build_ignored_attribute(:posts_count), build_non_ignored_attribute(:last_name), build_association(:avatar) ) expect(list.non_ignored.names).to eq [:last_name, :avatar] end it "knows all its #names for #associations" do list = build_attribute_list( build_ignored_attribute(:posts_count), build_non_ignored_attribute(:last_name), build_association(:avatar) ) expect(list.associations.names).to eq [:avatar] end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/decorator/attribute_hash_spec.rb
spec/factory_bot/decorator/attribute_hash_spec.rb
describe FactoryBot::Decorator::AttributeHash do describe "#attributes" do it "returns a hash of attributes" do attributes = {attribute_1: :value, attribute_2: :value} component = double(:component, attributes) decorator = described_class.new(component, [:attribute_1, :attribute_2]) expect(decorator.attributes).to eq(attributes) end context "with an attribute called 'attributes'" do it "does not call itself recursively" do attributes = {attributes: :value} component = double(:component, attributes) decorator = described_class.new(component, [:attributes]) expect(decorator.attributes).to eq(attributes) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/declaration/association_spec.rb
spec/factory_bot/declaration/association_spec.rb
describe FactoryBot::Declaration::Association do describe "#==" do context "when the attributes are equal" do it "the objects are equal" do declaration = described_class.new(:name, options: true) other_declaration = described_class.new(:name, options: true) expect(declaration).to eq(other_declaration) end end context "when the names are different" do it "the objects are NOT equal" do declaration = described_class.new(:name, options: true) other_declaration = described_class.new(:other_name, options: true) expect(declaration).not_to eq(other_declaration) end end context "when the options are different" do it "the objects are NOT equal" do declaration = described_class.new(:name, options: true) other_declaration = described_class.new(:name, other_options: true) expect(declaration).not_to eq(other_declaration) end end context "when comparing against another type of object" do it "the objects are NOT equal" do declaration = described_class.new(:name) expect(declaration).not_to eq(:not_a_declaration) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/declaration/implicit_spec.rb
spec/factory_bot/declaration/implicit_spec.rb
describe FactoryBot::Declaration::Implicit do context "with a known factory" do it "creates an association attribute" do allow(FactoryBot.factories).to receive(:registered?).and_return true declaration = FactoryBot::Declaration::Implicit.new(:name) attribute = declaration.to_attributes.first expect(attribute).to be_association end it "has the correct factory name" do allow(FactoryBot.factories).to receive(:registered?).and_return true name = :factory_name declaration = FactoryBot::Declaration::Implicit.new(name) attribute = declaration.to_attributes.first expect(attribute.factory).to eq(name) end end context "with a known sequence" do it "does not create an association attribute" do allow(FactoryBot::Internal.sequences).to receive(:registered?).and_return true declaration = FactoryBot::Declaration::Implicit.new(:name) attribute = declaration.to_attributes.first expect(attribute).not_to be_association end it "creates a sequence attribute" do allow(FactoryBot::Internal.sequences).to receive(:registered?).and_return true declaration = FactoryBot::Declaration::Implicit.new(:name) attribute = declaration.to_attributes.first expect(attribute).to be_a(FactoryBot::Attribute::Sequence) end end describe "#==" do context "when the attributes are equal" do it "the objects are equal" do declaration = described_class.new(:name, :factory, false) other_declaration = described_class.new(:name, :factory, false) expect(declaration).to eq(other_declaration) end end context "when the names are different" do it "the objects are NOT equal" do declaration = described_class.new(:name, :factory, false) other_declaration = described_class.new(:other_name, :factory, false) expect(declaration).not_to eq(other_declaration) end end context "when the factories are different" do it "the objects are NOT equal" do declaration = described_class.new(:name, :factory, false) other_declaration = described_class.new(:name, :other_factory, false) expect(declaration).not_to eq(other_declaration) end end context "when one is ignored and the other isn't" do it "the objects are NOT equal" do declaration = described_class.new(:name, :factory, false) other_declaration = described_class.new(:name, :factory, true) expect(declaration).not_to eq(other_declaration) end end context "when comparing against another type of object" do it "the objects are NOT equal" do declaration = described_class.new(:name, :factory, false) expect(declaration).not_to eq(:not_a_declaration) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/declaration/dynamic_spec.rb
spec/factory_bot/declaration/dynamic_spec.rb
describe FactoryBot::Declaration::Dynamic do describe "#==" do context "when the attributes are equal" do it "the objects are equal" do block = -> {} declaration = described_class.new(:name, false, block) other_declaration = described_class.new(:name, false, block) expect(declaration).to eq(other_declaration) end end context "when the names are different" do it "the objects are NOT equal" do block = -> {} declaration = described_class.new(:name, false, block) other_declaration = described_class.new(:other_name, false, block) expect(declaration).not_to eq(other_declaration) end end context "when the blocks are different" do it "the objects are NOT equal" do declaration = described_class.new(:name, false, -> {}) other_declaration = described_class.new(:name, false, -> {}) expect(declaration).not_to eq(other_declaration) end end context "when one is ignored and the other isn't" do it "the objects are NOT equal" do block = -> {} declaration = described_class.new(:name, false, block) other_declaration = described_class.new(:name, true, block) expect(declaration).not_to eq(other_declaration) end end context "when comparing against another type of object" do it "the objects are NOT equal" do declaration = described_class.new(:name, false, -> {}) expect(declaration).not_to eq(:not_a_declaration) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/strategy/build_spec.rb
spec/factory_bot/strategy/build_spec.rb
describe FactoryBot::Strategy::Build do it_should_behave_like "strategy with association support", :create it_should_behave_like "strategy with callbacks", :after_build it_should_behave_like "strategy with strategy: :build", :build end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/strategy/stub_spec.rb
spec/factory_bot/strategy/stub_spec.rb
shared_examples "disabled persistence method" do |method_name| let(:instance) { described_class.new.result(evaluation) } describe "overriding persistence method: ##{method_name}" do it "overrides the method with any arity" do method = instance.method(method_name) expect(method.arity).to eq(-1) end it "raises an informative error if the method is called" do expect { instance.send(method_name) }.to raise_error( RuntimeError, "stubbed models are not allowed to access the database - #{instance.class}##{method_name}()" ) end end end describe FactoryBot::Strategy::Stub do it_should_behave_like "strategy with association support", :build_stubbed it_should_behave_like "strategy with callbacks", :after_stub it_should_behave_like "strategy with strategy: :build", :build_stubbed context "asking for a result" do let(:result_instance) do define_class("ResultInstance") { attr_accessor :id, :created_at }.new end let(:evaluation) do double("evaluation", object: result_instance, notify: true) end it { expect(subject.result(evaluation)).not_to be_new_record } it { expect(subject.result(evaluation)).to be_persisted } it { expect(subject.result(evaluation)).not_to be_destroyed } it "assigns created_at" do created_at1 = subject.result(evaluation).created_at created_at2 = subject.result(evaluation).created_at expect(created_at1).to equal created_at2 end include_examples "disabled persistence method", :connection include_examples "disabled persistence method", :decrement! include_examples "disabled persistence method", :delete include_examples "disabled persistence method", :destroy include_examples "disabled persistence method", :destroy! include_examples "disabled persistence method", :increment! include_examples "disabled persistence method", :reload include_examples "disabled persistence method", :save include_examples "disabled persistence method", :save! include_examples "disabled persistence method", :toggle! include_examples "disabled persistence method", :touch include_examples "disabled persistence method", :update include_examples "disabled persistence method", :update! include_examples "disabled persistence method", :update_attribute include_examples "disabled persistence method", :update_attributes include_examples "disabled persistence method", :update_attributes! include_examples "disabled persistence method", :update_column include_examples "disabled persistence method", :update_columns end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/strategy/create_spec.rb
spec/factory_bot/strategy/create_spec.rb
describe FactoryBot::Strategy::Create do it_should_behave_like "strategy with association support", :create it_should_behave_like "strategy with callbacks", :after_build, :before_create, :after_create it "runs a custom create block" do evaluation = double( "evaluation", object: nil, notify: nil, create: nil ) subject.result(evaluation) expect(evaluation).to have_received(:create).once end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/strategy/attributes_for_spec.rb
spec/factory_bot/strategy/attributes_for_spec.rb
describe FactoryBot::Strategy::AttributesFor do let(:result) { {name: "John Doe", gender: "Male", admin: false} } let(:evaluation) { double("evaluation", hash: result) } it_should_behave_like "strategy without association support" it "returns the hash from the evaluation" do expect(subject.result(evaluation)).to eq result end it "does not run the to_create block" do expect { subject.result(evaluation) }.to_not raise_error end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute/association_spec.rb
spec/factory_bot/attribute/association_spec.rb
describe FactoryBot::Attribute::Association do let(:name) { :author } let(:factory) { :user } let(:overrides) { {first_name: "John"} } let(:association) { double("association") } subject { FactoryBot::Attribute::Association.new(name, factory, overrides) } before do # Define an '#association' instance method allowing it to be mocked. # Usually this is determined via '#method_missing' missing_methods = Module.new { def association(*args) end } subject.extend(missing_methods) allow(subject) .to receive(:association).with(any_args).and_return association end it { should be_association } its(:name) { should eq name } it "builds the association when calling the proc" do expect(subject.to_proc.call).to eq association end it "builds the association when calling the proc" do subject.to_proc.call expect(subject).to have_received(:association).with(factory, overrides) end end describe FactoryBot::Attribute::Association, "with a string name" do subject { FactoryBot::Attribute::Association.new("name", :user, {}) } its(:name) { should eq :name } end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute/sequence_spec.rb
spec/factory_bot/attribute/sequence_spec.rb
describe FactoryBot::Attribute::Sequence do let(:sequence_name) { :name } let(:name) { :first_name } let(:sequence) { FactoryBot::Sequence.new(sequence_name, 5) { |n| "Name #{n}" } } subject { FactoryBot::Attribute::Sequence.new(name, sequence_name, false) } before { FactoryBot::Internal.register_sequence(sequence) } its(:name) { should eq name } it "assigns the next value in the sequence" do expect(subject.to_proc.call).to eq "Name 5" end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/spec/factory_bot/attribute/dynamic_spec.rb
spec/factory_bot/attribute/dynamic_spec.rb
describe FactoryBot::Attribute::Dynamic do let(:name) { :first_name } let(:block) { -> {} } subject { FactoryBot::Attribute::Dynamic.new(name, false, block) } its(:name) { should eq name } context "with a block returning a static value" do let(:block) { -> { "value" } } it "returns the value when executing the proc" do expect(subject.to_proc.call).to eq "value" end end context "with a block returning its block-level variable" do let(:block) { ->(thing) { thing } } it "returns self when executing the proc" do expect(subject.to_proc.call).to eq subject end end context "with a block referencing an attribute on the attribute" do let(:block) { -> { attribute_defined_on_attribute } } let(:result) { "other attribute value" } before do # Define an '#attribute_defined_on_attribute' instance method allowing it # be mocked. Usually this is determined via '#method_missing' missing_methods = Module.new { def attribute_defined_on_attribute(*args) end } subject.extend(missing_methods) allow(subject) .to receive(:attribute_defined_on_attribute).and_return result end it "evaluates the attribute from the attribute" do expect(subject.to_proc.call).to eq result end end context "with a block returning a sequence" do let(:block) do -> do FactoryBot::Internal.register_sequence( FactoryBot::Sequence.new(:email, 1) { |n| "foo#{n}" } ) end end it "raises a sequence abuse error" do expect { subject.to_proc.call }.to raise_error(FactoryBot::SequenceAbuseError) end end end describe FactoryBot::Attribute::Dynamic, "with a string name" do subject { FactoryBot::Attribute::Dynamic.new("name", false, -> {}) } its(:name) { should eq :name } end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot.rb
lib/factory_bot.rb
require "set" require "active_support" require "active_support/core_ext/module/delegation" require "active_support/core_ext/module/attribute_accessors" require "active_support/deprecation" require "active_support/notifications" require "factory_bot/internal" require "factory_bot/definition_hierarchy" require "factory_bot/configuration" require "factory_bot/errors" require "factory_bot/factory_runner" require "factory_bot/strategy_syntax_method_registrar" require "factory_bot/strategy" require "factory_bot/registry" require "factory_bot/null_factory" require "factory_bot/null_object" require "factory_bot/evaluation" require "factory_bot/factory" require "factory_bot/attribute_assigner" require "factory_bot/evaluator" require "factory_bot/evaluator_class_definer" require "factory_bot/attribute" require "factory_bot/callback" require "factory_bot/callbacks_observer" require "factory_bot/declaration_list" require "factory_bot/declaration" require "factory_bot/sequence" require "factory_bot/attribute_list" require "factory_bot/trait" require "factory_bot/enum" require "factory_bot/aliases" require "factory_bot/definition" require "factory_bot/definition_proxy" require "factory_bot/syntax" require "factory_bot/syntax_runner" require "factory_bot/find_definitions" require "factory_bot/reload" require "factory_bot/decorator" require "factory_bot/decorator/attribute_hash" require "factory_bot/decorator/disallows_duplicates_registry" require "factory_bot/decorator/invocation_tracker" require "factory_bot/decorator/new_constructor" require "factory_bot/uri_manager" require "factory_bot/linter" require "factory_bot/version" module FactoryBot Deprecation = ActiveSupport::Deprecation.new("7.0", "factory_bot") mattr_accessor :use_parent_strategy, instance_accessor: false self.use_parent_strategy = true mattr_accessor :automatically_define_enum_traits, instance_accessor: false self.automatically_define_enum_traits = true mattr_accessor :sequence_setting_timeout, instance_accessor: false self.sequence_setting_timeout = 3 # Look for errors in factories and (optionally) their traits. # Parameters: # factories - which factories to lint; omit for all factories # options: # traits: true - to lint traits as well as factories # strategy: :create - to specify the strategy for linting # verbose: true - to include full backtraces for each linting error def self.lint(*args) options = args.extract_options! factories_to_lint = args[0] || FactoryBot.factories Linter.new(factories_to_lint, **options).lint! end # Set the starting value for ids when using the build_stubbed strategy # # @param [Integer] starting_id The new starting id value. def self.build_stubbed_starting_id=(starting_id) Strategy::Stub.next_id = starting_id - 1 end class << self # @!method rewind_sequence(*uri_parts) # Rewind an individual global or inline sequence. # # @param [Array<Symbol>, String] uri_parts The components of the sequence URI. # # @example Rewinding a sequence by its URI parts # rewind_sequence(:factory_name, :trait_name, :sequence_name) # # @example Rewinding a sequence by its URI string # rewind_sequence("factory_name/trait_name/sequence_name") # # @!method set_sequence(*uri_parts, value) # Set the sequence to a specific value, providing the new value is within # the sequence set. # # @param [Array<Symbol>, String] uri_parts The components of the sequence URI. # @param [Object] value The new value for the sequence. This must be a value that is # within the sequence definition. For example, you cannot set # a String sequence to an Integer value. # # @example # set_sequence(:factory_name, :trait_name, :sequence_name, 450) # @example # set_sequence([:factory_name, :trait_name, :sequence_name], 450) # @example # set_sequence("factory_name/trait_name/sequence_name", 450) delegate :factories, :register_strategy, :rewind_sequences, :rewind_sequence, :set_sequence, :strategy_by_name, to: Internal end end FactoryBot::Internal.register_default_strategies
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/reload.rb
lib/factory_bot/reload.rb
module FactoryBot def self.reload Internal.reset_configuration Internal.register_default_strategies find_definitions end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/callback.rb
lib/factory_bot/callback.rb
module FactoryBot class Callback attr_reader :name def initialize(name, block) @name = name.to_sym @block = block end def run(instance, evaluator) case block.arity when 1, -1, -2 then syntax_runner.instance_exec(instance, &block) when 2 then syntax_runner.instance_exec(instance, evaluator, &block) else syntax_runner.instance_exec(&block) end end def ==(other) name == other.name && block == other.block end protected attr_reader :block private def syntax_runner @syntax_runner ||= SyntaxRunner.new end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/syntax.rb
lib/factory_bot/syntax.rb
require "factory_bot/syntax/methods" require "factory_bot/syntax/default" module FactoryBot module Syntax end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/version.rb
lib/factory_bot/version.rb
module FactoryBot VERSION = "6.5.6".freeze end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/errors.rb
lib/factory_bot/errors.rb
module FactoryBot # Raised when a factory is defined that attempts to instantiate itself. class AssociationDefinitionError < RuntimeError; end # Raised when a trait is defined that references itself. class TraitDefinitionError < RuntimeError; end # Raised when a callback is defined that has an invalid name class InvalidCallbackNameError < RuntimeError; end # Raised when a factory is defined with the same name as a previously-defined factory. class DuplicateDefinitionError < RuntimeError; end # Raised when attempting to register a sequence from a dynamic attribute block class SequenceAbuseError < RuntimeError; end # Raised when defining an attribute twice in the same factory class AttributeDefinitionError < RuntimeError; end # Raised when attempting to pass a block to an association definition class AssociationDefinitionError < RuntimeError; end # Raised when a method is defined in a factory or trait with arguments class MethodDefinitionError < RuntimeError; end # Raised when any factory is considered invalid class InvalidFactoryError < RuntimeError; end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/strategy.rb
lib/factory_bot/strategy.rb
require "factory_bot/strategy/build" require "factory_bot/strategy/create" require "factory_bot/strategy/attributes_for" require "factory_bot/strategy/stub" require "factory_bot/strategy/null" module FactoryBot module Strategy def self.lookup_strategy(name_or_object) return name_or_object if name_or_object.is_a?(Class) FactoryBot::Internal.strategy_by_name(name_or_object) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/definition_hierarchy.rb
lib/factory_bot/definition_hierarchy.rb
module FactoryBot class DefinitionHierarchy delegate :callbacks, :constructor, :to_create, to: Internal def self.build_from_definition(definition) build_to_create(&definition.to_create) build_constructor(&definition.constructor) add_callbacks definition.callbacks end def self.add_callbacks(callbacks) if callbacks.any? define_method :callbacks do super() + callbacks end end end private_class_method :add_callbacks def self.build_constructor(&block) if block define_method(:constructor) do block end end end private_class_method :build_constructor def self.build_to_create(&block) if block define_method(:to_create) do block end end end private_class_method :build_to_create end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/uri_manager.rb
lib/factory_bot/uri_manager.rb
module FactoryBot # @api private class UriManager attr_reader :endpoints, :paths, :uri_list delegate :size, :any?, :empty?, :each?, :include?, :first, to: :@uri_list delegate :build_uri, to: :class # Concatenate the parts, sripping leading/following slashes # and returning a Symbolized String or nil. # # Example: # build_uri(:my_factory, :my_trait, :my_sequence) # #=> :"myfactory/my_trait/my_sequence" # def self.build_uri(*parts) return nil if parts.empty? parts.join("/") .sub(/\A\/+/, "") .sub(/\/+\z/, "") .tr(" ", "_") .to_sym end # Configures the new UriManager # # Arguments: # endpoints: (Array of Strings or Symbols) # the objects endpoints. # # paths: (Array of Strings or Symbols) # the parent URIs to prepend to each endpoint # def initialize(*endpoints, paths: []) if endpoints.empty? fail ArgumentError, "wrong number of arguments (given 0, expected 1+)" end @uri_list = [] @endpoints = endpoints.flatten @paths = Array(paths).flatten build_uri_list end def to_a @uri_list.dup end private def build_uri_list @endpoints.each do |endpoint| if @paths.any? @paths.each { |path| @uri_list << build_uri(path, endpoint) } else @uri_list << build_uri(endpoint) end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/callbacks_observer.rb
lib/factory_bot/callbacks_observer.rb
module FactoryBot # @api private class CallbacksObserver def initialize(callbacks, evaluator) @callbacks = callbacks @evaluator = evaluator @completed = [] end def update(name, result_instance) callbacks_by_name(name).each do |callback| if !completed?(result_instance, callback) callback.run(result_instance, @evaluator) record_completion!(result_instance, callback) end end end private def callbacks_by_name(name) @callbacks.select { |callback| callback.name == name } end def completed?(instance, callback) key = completion_key_for(instance, callback) @completed.include?(key) end def record_completion!(instance, callback) key = completion_key_for(instance, callback) @completed << key end def completion_key_for(instance, callback) "#{instance.object_id}-#{callback.object_id}" end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute.rb
lib/factory_bot/attribute.rb
require "factory_bot/attribute/dynamic" require "factory_bot/attribute/association" require "factory_bot/attribute/sequence" module FactoryBot # @api private class Attribute attr_reader :name, :ignored def initialize(name, ignored) @name = name.to_sym @ignored = ignored end def to_proc -> {} end def association? false end def alias_for?(attr) FactoryBot.aliases_for(attr).include?(name) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute_list.rb
lib/factory_bot/attribute_list.rb
module FactoryBot # @api private class AttributeList include Enumerable def initialize(name = nil, attributes = []) @name = name @attributes = attributes end def define_attribute(attribute) ensure_attribute_not_self_referencing! attribute ensure_attribute_not_defined! attribute add_attribute attribute end def each(&block) @attributes.each(&block) end def names map(&:name) end def associations AttributeList.new(@name, select(&:association?)) end def ignored AttributeList.new(@name, select(&:ignored)) end def non_ignored AttributeList.new(@name, reject(&:ignored)) end def apply_attributes(attributes_to_apply) attributes_to_apply.each { |attribute| add_attribute(attribute) } end private def add_attribute(attribute) @attributes << attribute attribute end def ensure_attribute_not_defined!(attribute) if attribute_defined?(attribute.name) raise AttributeDefinitionError, "Attribute already defined: #{attribute.name}" end end def ensure_attribute_not_self_referencing!(attribute) if attribute.respond_to?(:factory) && attribute.factory == @name message = "Self-referencing association '#{attribute.name}' in '#{attribute.factory}'" raise AssociationDefinitionError, message end end def attribute_defined?(attribute_name) @attributes.any? do |attribute| attribute.name == attribute_name end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/factory_runner.rb
lib/factory_bot/factory_runner.rb
module FactoryBot class FactoryRunner def initialize(name, strategy, traits_and_overrides) @name = name @strategy = strategy @overrides = traits_and_overrides.extract_options! @traits = traits_and_overrides end def run(runner_strategy = @strategy, &block) factory = FactoryBot::Internal.factory_by_name(@name) factory.compile if @traits.any? factory = factory.with_traits(@traits) end instrumentation_payload = { name: @name, strategy: runner_strategy, traits: @traits, overrides: @overrides, factory: factory } ActiveSupport::Notifications.instrument("factory_bot.run_factory", instrumentation_payload) do factory.run(runner_strategy, @overrides, &block) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/registry.rb
lib/factory_bot/registry.rb
require "active_support/hash_with_indifferent_access" module FactoryBot class Registry include Enumerable attr_reader :name def initialize(name) @name = name @items = ActiveSupport::HashWithIndifferentAccess.new end def clear @items.clear end def each(&block) @items.values.uniq.each(&block) end def find(name) @items.fetch(name) rescue KeyError => e raise key_error_with_custom_message(e) end alias_method :[], :find def register(name, item) @items[name] = item end def registered?(name) @items.key?(name) end private def key_error_with_custom_message(key_error) message = key_error.message.sub("key not found", "#{@name} not registered") new_key_error(message, key_error).tap do |error| error.set_backtrace(key_error.backtrace) end end # detailed_message introduced in Ruby 3.2 for cleaner integration with # did_you_mean. See https://bugs.ruby-lang.org/issues/18564 if KeyError.method_defined?(:detailed_message) def new_key_error(message, key_error) KeyError.new(message, key: key_error.key, receiver: key_error.receiver) end else def new_key_error(message, _) KeyError.new(message) end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/attribute_assigner.rb
lib/factory_bot/attribute_assigner.rb
module FactoryBot # @api private class AttributeAssigner def initialize(evaluator, build_class, &instance_builder) @build_class = build_class @instance_builder = instance_builder @evaluator = evaluator @attribute_list = evaluator.class.attribute_list @attribute_names_assigned = [] end # constructs an object-based factory product def object @evaluator.instance = build_class_instance build_class_instance.tap do |instance| attributes_to_set_on_instance.each do |attribute| instance.public_send(:"#{attribute}=", get(attribute)) @attribute_names_assigned << attribute end end end # constructs a Hash-based factory product def hash @evaluator.instance = build_hash attributes_to_set_on_hash.each_with_object({}) do |attribute, result| result[attribute] = get(attribute) end end private # Track evaluation of methods on the evaluator to prevent the duplicate # assignment of attributes accessed and via `initialize_with` syntax def method_tracking_evaluator @method_tracking_evaluator ||= Decorator::AttributeHash.new( decorated_evaluator, attribute_names_to_assign ) end def decorated_evaluator Decorator::NewConstructor.new( Decorator::InvocationTracker.new(@evaluator), @build_class ) end def methods_invoked_on_evaluator method_tracking_evaluator.__invoked_methods__ end def build_class_instance @build_class_instance ||= method_tracking_evaluator.instance_exec(&@instance_builder) end def build_hash @build_hash ||= NullObject.new(hash_instance_methods_to_respond_to) end def get(attribute_name) @evaluator.send(attribute_name) end def attributes_to_set_on_instance (attribute_names_to_assign - @attribute_names_assigned - methods_invoked_on_evaluator).uniq end def attributes_to_set_on_hash attribute_names_to_assign - association_names end # Builds a list of attributes names that should be assigned to the factory product def attribute_names_to_assign @attribute_names_to_assign ||= begin # start a list of candidates containing non-transient attributes and overrides assignment_candidates = non_ignored_attribute_names + override_names # then remove any transient attributes (potentially reintroduced by the overrides), # and remove ignorable aliased attributes from the candidate list assignment_candidates - ignored_attribute_names - attribute_names_overriden_by_alias end end def non_ignored_attribute_names @attribute_list.non_ignored.names end def ignored_attribute_names @attribute_list.ignored.names end def association_names @attribute_list.associations.names end def override_names @evaluator.__override_names__ end def attribute_names @attribute_list.names end def hash_instance_methods_to_respond_to attribute_names + override_names + @build_class.instance_methods end # Builds a list of attribute names which are slated to be interrupted by an override. def attribute_names_overriden_by_alias @attribute_list .non_ignored .flat_map { |attribute| override_names.map do |override| attribute.name if ignorable_alias?(attribute, override) end } .compact end # Is the attribute an ignorable alias of the override? # An attribute is ignorable when it is an alias of the override AND it is # either interrupting an assocciation OR is not the name of another attribute # # @note An "alias" is currently an overloaded term for two distinct cases: # (1) attributes which are aliases and reference the same value # (2) a logical grouping of a foreign key and an associated object def ignorable_alias?(attribute, override) return false unless attribute.alias_for?(override) # The attribute alias should be ignored when the override interrupts an association return true if override_interrupts_association?(attribute, override) # Remaining aliases should be ignored when the override does not match a declared attribute. # An override which is an alias to a declared attribute should not interrupt the aliased # attribute and interrupt only the attribute with a matching name. This workaround allows a # factory to declare both <attribute> and <attribute>_id as separate and distinct attributes. !override_matches_declared_attribute?(override) end # Does this override interrupt an association? # When true, this indicates the aliased attribute is related to a declared association and the # override does not match the attribute name. # # @note Association overrides should take precedence over a declared foreign key attribute. # # @note An override may interrupt an association by providing the associated object or # by providing the foreign key. # # @param [FactoryBot::Attribute] aliased_attribute # @param [Symbol] override name of an override which is an alias to the attribute name def override_interrupts_association?(aliased_attribute, override) (aliased_attribute.association? || association_names.include?(override)) && aliased_attribute.name != override end # Does this override match the name of any declared attribute? # # @note Checking against the names of all attributes, resolves any issues with having both # <attribute> and <attribute>_id in the same factory. This also takes into account ignored # attributes that should not be assigned (aka transient attributes) # # @param [Symbol] override the name of an override def override_matches_declared_attribute?(override) attribute_names.include?(override) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/sequence.rb
lib/factory_bot/sequence.rb
require "timeout" module FactoryBot # Sequences are defined using sequence within a FactoryBot.define block. # Sequence values are generated using next. # @api private class Sequence attr_reader :name, :uri_manager, :aliases def self.find(*uri_parts) if uri_parts.empty? fail ArgumentError, "wrong number of arguments, expected 1+)" else find_by_uri FactoryBot::UriManager.build_uri(*uri_parts) end end def self.find_by_uri(uri) uri = uri.to_sym FactoryBot::Internal.sequences.to_a.find { |seq| seq.has_uri?(uri) } || FactoryBot::Internal.inline_sequences.find { |seq| seq.has_uri?(uri) } end def initialize(name, *args, &proc) options = args.extract_options! @name = name @proc = proc @aliases = options.fetch(:aliases, []).map(&:to_sym) @uri_manager = FactoryBot::UriManager.new(names, paths: options[:uri_paths]) @value = args.first || 1 unless @value.respond_to?(:peek) @value = EnumeratorAdapter.new(@value) end end def next(scope = nil) if @proc && scope scope.instance_exec(value, &@proc) elsif @proc @proc.call(value) else value end ensure increment_value end def names [@name] + @aliases end def has_name?(test_name) names.include?(test_name.to_sym) end def has_uri?(uri) uri_manager.include?(uri) end def for_factory?(test_factory_name) FactoryBot::Internal.factory_by_name(factory_name).names.include?(test_factory_name.to_sym) end def rewind @value.rewind end ## # If it's an Integer based sequence, set the new value directly, # else rewind and seek from the beginning until a match is found. # def set_value(new_value) if can_set_value_directly?(new_value) @value.set_value(new_value) elsif can_set_value_by_index? set_value_by_index(new_value) else seek_value(new_value) end end protected attr_reader :proc private def value @value.peek end def increment_value @value.next end def can_set_value_by_index? @value.respond_to?(:find_index) end ## # Set to the given value, or fail if not found # def set_value_by_index(value) index = @value.find_index(value) || fail_value_not_found(value) @value.rewind index.times { @value.next } end ## # Rewind index and seek until the value is found or the max attempts # have been tried. If not found, the sequence is rewound to its original value # def seek_value(value) original_value = @value.peek # rewind and search for the new value @value.rewind Timeout.timeout(FactoryBot.sequence_setting_timeout) do loop do return if @value.peek == value increment_value end # loop auto-recues a StopIteration error, so if we # reached this point, re-raise it now fail StopIteration end rescue Timeout::Error, StopIteration reset_original_value(original_value) fail_value_not_found(value) end def reset_original_value(original_value) @value.rewind until @value.peek == original_value increment_value end end def can_set_value_directly?(value) return false unless value.is_a?(Integer) return false unless @value.is_a?(EnumeratorAdapter) @value.integer_value? end def fail_value_not_found(value) fail ArgumentError, "Unable to find '#{value}' in the sequence." end class EnumeratorAdapter def initialize(initial_value) @initial_value = initial_value end def peek value end def next @value = value.next end def rewind @value = first_value end def set_value(new_value) if new_value >= first_value @value = new_value else fail ArgumentError, "Value cannot be less than: #{@first_value}" end end def integer_value? first_value.is_a?(Integer) end private def first_value @first_value ||= initial_value end def value @value ||= initial_value end def initial_value @value = @initial_value.respond_to?(:call) ? @initial_value.call : @initial_value @first_value = @value end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/evaluator_class_definer.rb
lib/factory_bot/evaluator_class_definer.rb
module FactoryBot # @api private class EvaluatorClassDefiner def initialize(attributes, parent_class) @parent_class = parent_class @attributes = attributes attributes.each do |attribute| evaluator_class.define_attribute(attribute.name, &attribute.to_proc) end end def evaluator_class @evaluator_class ||= Class.new(@parent_class).tap do |klass| klass.attribute_lists ||= [] klass.attribute_lists += [@attributes] end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/configuration.rb
lib/factory_bot/configuration.rb
module FactoryBot # @api private class Configuration attr_reader( :callback_names, :factories, :inline_sequences, :sequences, :strategies, :traits ) def initialize @factories = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Factory")) @sequences = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Sequence")) @traits = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Trait")) @strategies = Registry.new("Strategy") @callback_names = Set.new @definition = Definition.new(:configuration) @inline_sequences = [] to_create(&:save!) initialize_with { new } end delegate :to_create, :skip_create, :constructor, :before, :after, :callback, :callbacks, to: :@definition def initialize_with(&block) @definition.define_constructor(&block) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/declaration.rb
lib/factory_bot/declaration.rb
require "factory_bot/declaration/dynamic" require "factory_bot/declaration/association" require "factory_bot/declaration/implicit" module FactoryBot # @api private class Declaration attr_reader :name def initialize(name, ignored = false) @name = name @ignored = ignored end def to_attributes build end protected attr_reader :ignored end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/linter.rb
lib/factory_bot/linter.rb
module FactoryBot class Linter def initialize(factories, strategy: :create, traits: false, verbose: false) @factories_to_lint = factories @factory_strategy = strategy @traits = traits @verbose = verbose @invalid_factories = calculate_invalid_factories end def lint! if invalid_factories.any? raise InvalidFactoryError, error_message end end private attr_reader :factories_to_lint, :invalid_factories, :factory_strategy def calculate_invalid_factories factories_to_lint.each_with_object(Hash.new([])) do |factory, result| errors = lint(factory) result[factory] |= errors unless errors.empty? end end class FactoryError def initialize(wrapped_error, factory) @wrapped_error = wrapped_error @factory = factory end def message message = @wrapped_error.message "* #{location} - #{message} (#{@wrapped_error.class.name})" end def verbose_message <<~MESSAGE #{message} #{@wrapped_error.backtrace.join("\n ")} MESSAGE end def location @factory.name end end class FactoryTraitError < FactoryError def initialize(wrapped_error, factory, trait_name) super(wrapped_error, factory) @trait_name = trait_name end def location "#{@factory.name}+#{@trait_name}" end end def lint(factory) if @traits lint_factory(factory) + lint_traits(factory) else lint_factory(factory) end end def lint_factory(factory) result = [] begin in_transaction { FactoryBot.public_send(factory_strategy, factory.name) } rescue => e result |= [FactoryError.new(e, factory)] end result end def lint_traits(factory) result = [] factory.definition.defined_traits.map(&:name).each do |trait_name| in_transaction { FactoryBot.public_send(factory_strategy, factory.name, trait_name) } rescue => e result |= [FactoryTraitError.new(e, factory, trait_name)] end result end def error_message lines = invalid_factories.map { |_factory, exceptions| exceptions.map(&error_message_type) }.flatten <<~ERROR_MESSAGE.strip The following factories are invalid: #{lines.join("\n")} ERROR_MESSAGE end def error_message_type if @verbose :verbose_message else :message end end def in_transaction if defined?(ActiveRecord::Base) ActiveRecord::Base.transaction(joinable: false) do yield raise ActiveRecord::Rollback end else yield end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/null_factory.rb
lib/factory_bot/null_factory.rb
module FactoryBot # @api private class NullFactory attr_reader :definition def initialize @definition = Definition.new(:null_factory) end delegate :defined_traits, :callbacks, :attributes, :constructor, :to_create, to: :definition def compile end def class_name end def evaluator_class FactoryBot::Evaluator end def hierarchy_class FactoryBot::DefinitionHierarchy end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/decorator.rb
lib/factory_bot/decorator.rb
module FactoryBot class Decorator < BasicObject undef_method :== def initialize(component) @component = component end def method_missing(...) # rubocop:disable Style/MethodMissingSuper @component.send(...) end def send(...) __send__(...) end def respond_to_missing?(name, include_private = false) @component.respond_to?(name, true) || super end def self.const_missing(name) ::Object.const_get(name) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/definition.rb
lib/factory_bot/definition.rb
module FactoryBot # @api private class Definition attr_reader :defined_traits, :declarations, :name, :registered_enums, :uri_manager attr_accessor :klass def initialize(name, base_traits = [], **opts) @name = name @uri_manager = opts[:uri_manager] @declarations = DeclarationList.new(name) @callbacks = [] @defined_traits = Set.new @registered_enums = [] @to_create = nil @base_traits = base_traits @additional_traits = [] @constructor = nil @attributes = nil @compiled = false @expanded_enum_traits = false end delegate :declare_attribute, to: :declarations def attributes @attributes ||= AttributeList.new.tap do |attribute_list| attribute_lists = aggregate_from_traits_and_self(:attributes) { declarations.attributes } attribute_lists.each do |attributes| attribute_list.apply_attributes attributes end end end def to_create(&block) if block @to_create = block else aggregate_from_traits_and_self(:to_create) { @to_create }.last end end def constructor aggregate_from_traits_and_self(:constructor) { @constructor }.last end def callbacks aggregate_from_traits_and_self(:callbacks) { @callbacks } end def compile(klass = nil) unless @compiled expand_enum_traits(klass) unless klass.nil? declarations.attributes self.klass ||= klass defined_traits.each do |defined_trait| defined_trait.klass ||= klass base_traits.each { |bt| bt.define_trait defined_trait } additional_traits.each { |at| at.define_trait defined_trait } end @compiled = true ActiveSupport::Notifications.instrument "factory_bot.compile_factory", { name: name, attributes: declarations.attributes, traits: defined_traits, class: klass || self.klass } end end def overridable declarations.overridable self end def inherit_traits(new_traits) @base_traits += new_traits end def append_traits(new_traits) @additional_traits += new_traits end def add_callback(callback) @callbacks << callback end def skip_create @to_create = ->(instance) {} end def define_trait(trait) @defined_traits.add(trait) end def defined_traits_names @defined_traits.map(&:name) end def register_enum(enum) @registered_enums << enum end def define_constructor(&block) @constructor = block end def before(*names, &block) callback(*names.map { |name| "before_#{name}" }, &block) end def after(*names, &block) callback(*names.map { |name| "after_#{name}" }, &block) end def callback(*names, &block) names.each do |name| add_callback(Callback.new(name, block)) end end private def base_traits @base_traits.map { |name| trait_by_name(name) } rescue KeyError => error raise error_with_definition_name(error) end # detailed_message introduced in Ruby 3.2 for cleaner integration with # did_you_mean. See https://bugs.ruby-lang.org/issues/18564 if KeyError.method_defined?(:detailed_message) def error_with_definition_name(error) message = error.message + " referenced within \"#{name}\" definition" error.class.new(message, key: error.key, receiver: error.receiver) .tap { |new_error| new_error.set_backtrace(error.backtrace) } end else def error_with_definition_name(error) message = error.message message.insert( message.index("\nDid you mean?") || message.length, " referenced within \"#{name}\" definition" ) error.class.new(message).tap do |new_error| new_error.set_backtrace(error.backtrace) end end end def additional_traits @additional_traits.map { |name| trait_by_name(name) } end def trait_by_name(name) trait_for(name) || Internal.trait_by_name(name, klass) end def trait_for(name) @defined_traits_by_name ||= defined_traits.each_with_object({}) { |t, memo| memo[t.name] ||= t } @defined_traits_by_name[name.to_s] end def initialize_copy(source) super @attributes = nil @compiled = false @defined_traits_by_name = nil end def aggregate_from_traits_and_self(method_name, &block) compile [ base_traits.map(&method_name), instance_exec(&block), additional_traits.map(&method_name) ].flatten.compact end def expand_enum_traits(klass) return if @expanded_enum_traits if automatically_register_defined_enums?(klass) automatically_register_defined_enums(klass) end registered_enums.each do |enum| traits = enum.build_traits(klass) traits.each { |trait| define_trait(trait) } end @expanded_enum_traits = true end def automatically_register_defined_enums(klass) klass.defined_enums.each_key { |name| register_enum(Enum.new(name)) } end def automatically_register_defined_enums?(klass) FactoryBot.automatically_define_enum_traits && klass.respond_to?(:defined_enums) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/enum.rb
lib/factory_bot/enum.rb
module FactoryBot # @api private class Enum def initialize(attribute_name, values = nil) @attribute_name = attribute_name @values = values end def build_traits(klass) enum_values(klass).map do |trait_name, value| build_trait(trait_name, @attribute_name, value || trait_name) end end private def enum_values(klass) @values || klass.send(@attribute_name.to_s.pluralize) end def build_trait(trait_name, attribute_name, value) Trait.new(trait_name) do add_attribute(attribute_name) { value } end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/syntax_runner.rb
lib/factory_bot/syntax_runner.rb
module FactoryBot # @api private class SyntaxRunner include Syntax::Methods end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/find_definitions.rb
lib/factory_bot/find_definitions.rb
module FactoryBot class << self # An Array of strings specifying locations that should be searched for # factory definitions. By default, factory_bot will attempt to require # "factories.rb", "factories/**/*.rb", "test/factories.rb", # "test/factories/**.rb", "spec/factories.rb", and "spec/factories/**.rb". attr_accessor :definition_file_paths end self.definition_file_paths = %w[factories test/factories spec/factories] def self.find_definitions absolute_definition_file_paths = definition_file_paths.map { |path| File.expand_path(path) } absolute_definition_file_paths.uniq.each do |path| load("#{path}.rb") if File.exist?("#{path}.rb") if File.directory? path Dir[File.join(path, "**", "*.rb")].sort.each do |file| load file end end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/null_object.rb
lib/factory_bot/null_object.rb
module FactoryBot # @api private class NullObject < ::BasicObject def initialize(methods_to_respond_to) @methods_to_respond_to = methods_to_respond_to.map(&:to_s) end def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing if respond_to?(name) nil else super end end def respond_to?(method) @methods_to_respond_to.include? method.to_s end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/aliases.rb
lib/factory_bot/aliases.rb
module FactoryBot class << self attr_accessor :aliases end self.aliases = [ [/(.+)_id/, '\1'], [/(.*)/, '\1_id'] ] def self.aliases_for(attribute) aliases.map { |(pattern, replace)| if pattern.match?(attribute) attribute.to_s.sub(pattern, replace).to_sym end }.compact << attribute end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/factory.rb
lib/factory_bot/factory.rb
require "active_support/core_ext/hash/keys" require "active_support/inflector" module FactoryBot # @api private class Factory attr_reader :name, :definition def initialize(name, options = {}) assert_valid_options(options) @name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym @parent = options[:parent] @aliases = options[:aliases] || [] @class_name = options[:class] @uri_manager = FactoryBot::UriManager.new(names) @definition = Definition.new(@name, options[:traits] || [], uri_manager: @uri_manager) @compiled = false end delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, :defined_traits, :defined_traits_names, :inherit_traits, :append_traits, to: :@definition def build_class @build_class ||= if class_name.is_a? Class class_name elsif class_name.to_s.safe_constantize class_name.to_s.safe_constantize else class_name.to_s.camelize.constantize end end def run(build_strategy, overrides, &block) block ||= ->(result) { result } compile strategy = Strategy.lookup_strategy(build_strategy).new evaluator = evaluator_class.new(strategy, overrides.symbolize_keys) attribute_assigner = AttributeAssigner.new(evaluator, build_class, &compiled_constructor) observer = CallbacksObserver.new(callbacks, evaluator) evaluation = Evaluation.new(evaluator, attribute_assigner, compiled_to_create, observer) evaluation.notify(:before_all, nil) instance = strategy.result(evaluation).tap(&block) evaluation.notify(:after_all, instance) instance end def human_names names.map { |name| name.to_s.humanize.downcase } end def associations evaluator_class.attribute_list.associations end # Names for this factory, including aliases. # # Example: # # factory :user, aliases: [:author] do # # ... # end # # FactoryBot.create(:author).class # # => User # # Because an attribute defined without a value or block will build an # association with the same name, this allows associations to be defined # without factories, such as: # # factory :user, aliases: [:author] do # # ... # end # # factory :post do # author # end # # FactoryBot.create(:post).author.class # # => User def names [name] + @aliases end def compile unless @compiled parent.compile inherit_parent_traits @definition.compile(build_class) build_hierarchy @compiled = true end end def with_traits(traits) clone.tap do |factory_with_traits| factory_with_traits.append_traits traits end end protected def class_name @class_name || parent.class_name || name end def evaluator_class @evaluator_class ||= EvaluatorClassDefiner.new(attributes, parent.evaluator_class).evaluator_class end def attributes compile AttributeList.new(@name).tap do |list| list.apply_attributes definition.attributes end end def hierarchy_class @hierarchy_class ||= Class.new(parent.hierarchy_class) end def hierarchy_instance @hierarchy_instance ||= hierarchy_class.new end def build_hierarchy hierarchy_class.build_from_definition definition end def callbacks hierarchy_instance.callbacks end def compiled_to_create hierarchy_instance.to_create end def compiled_constructor hierarchy_instance.constructor end private def assert_valid_options(options) options.assert_valid_keys(:class, :parent, :aliases, :traits) end def parent if @parent FactoryBot::Internal.factory_by_name(@parent) else NullFactory.new end end def inherit_parent_traits parent.defined_traits.each do |trait| next if defined_traits_names.include?(trait.name) define_trait(trait.clone) end end def initialize_copy(source) super @definition = @definition.clone @evaluator_class = nil @hierarchy_class = nil @hierarchy_instance = nil @compiled = false end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/internal.rb
lib/factory_bot/internal.rb
module FactoryBot # @api private module Internal class << self delegate :after, :before, :callbacks, :constructor, :factories, :initialize_with, :inline_sequences, :sequences, :skip_create, :strategies, :to_create, :traits, to: :configuration def configuration @configuration ||= Configuration.new end def reset_configuration @configuration = nil end def register_inline_sequence(sequence) inline_sequences.push(sequence) sequence end def rewind_inline_sequences inline_sequences.each(&:rewind) end def register_trait(trait) trait.names.each do |name| traits.register(name, trait) end trait end def trait_by_name(name, klass) traits.find(name).tap { |t| t.klass = klass } end def register_sequence(sequence) sequence.names.each do |name| sequences.register(name, sequence) end sequence end def sequence_by_name(name) sequences.find(name) end def rewind_sequences sequences.each(&:rewind) rewind_inline_sequences end def rewind_sequence(*uri_parts) fail_argument_count(0, "1+") if uri_parts.empty? uri = build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || fail_unregistered_sequence(uri) sequence.rewind end def set_sequence(*uri_parts, value) uri = build_uri(uri_parts) || fail_argument_count(uri_parts.size, "2+") sequence = Sequence.find(*uri) || fail_unregistered_sequence(uri) sequence.set_value(value) end def register_factory(factory) factory.names.each do |name| factories.register(name, factory) end factory end def factory_by_name(name) factories.find(name) end def register_strategy(strategy_name, strategy_class) strategies.register(strategy_name, strategy_class) StrategySyntaxMethodRegistrar.new(strategy_name).define_strategy_methods end def strategy_by_name(name) strategies.find(name) end def register_default_strategies register_strategy(:build, FactoryBot::Strategy::Build) register_strategy(:create, FactoryBot::Strategy::Create) register_strategy(:attributes_for, FactoryBot::Strategy::AttributesFor) register_strategy(:build_stubbed, FactoryBot::Strategy::Stub) register_strategy(:null, FactoryBot::Strategy::Null) end private def build_uri(...) FactoryBot::UriManager.build_uri(...) end def fail_argument_count(received, expected) fail ArgumentError, "wrong number of arguments (given #{received}, expected #{expected})" end def fail_unregistered_sequence(uri) fail KeyError, "Sequence not registered: '#{uri}'." end end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/definition_proxy.rb
lib/factory_bot/definition_proxy.rb
module FactoryBot class DefinitionProxy UNPROXIED_METHODS = %w[ __send__ __id__ nil? send object_id extend instance_eval initialize block_given? raise caller method ].freeze (instance_methods + private_instance_methods).each do |method| undef_method(method) unless UNPROXIED_METHODS.include?(method.to_s) end delegate :before, :after, :callback, to: :@definition attr_reader :child_factories def initialize(definition, ignore = false) @definition = definition @ignore = ignore @child_factories = [] end def singleton_method_added(name) message = "Defining methods in blocks (trait or factory) is not supported (#{name})" raise FactoryBot::MethodDefinitionError, message end # Adds an attribute to the factory. # The attribute value will be generated "lazily" # by calling the block whenever an instance is generated. # The block will not be called if the # attribute is overridden for a specific instance. # # Arguments: # * name: +Symbol+ or +String+ # The name of this attribute. This will be assigned using "name=" for # generated instances. def add_attribute(name, &block) declaration = Declaration::Dynamic.new(name, @ignore, block) @definition.declare_attribute(declaration) end def transient(&block) proxy = DefinitionProxy.new(@definition, true) proxy.instance_eval(&block) end # Calls add_attribute using the missing method name as the name of the # attribute, so that: # # factory :user do # name { 'Billy Idol' } # end # # and: # # factory :user do # add_attribute(:name) { 'Billy Idol' } # end # # are equivalent. # # If no argument or block is given, factory_bot will first look for an # association, then for a sequence, and finally for a trait with the same # name. This means that given an "admin" trait, an "email" sequence, and an # "account" factory: # # factory :user, traits: [:admin] do # email { generate(:email) } # association :account # end # # and: # # factory :user do # admin # email # account # end # # are equivalent. def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing association_options = args.first if association_options.nil? __declare_attribute__(name, block) elsif __valid_association_options?(association_options) association(name, association_options) else raise NoMethodError.new(<<~MSG) undefined method '#{name}' in '#{@definition.name}' factory Did you mean? '#{name} { #{association_options.inspect} }' MSG end end # Adds an attribute that will have unique values generated by a sequence with # a specified format. # # The result of: # factory :user do # sequence(:email) { |n| "person#{n}@example.com" } # end # # Is equal to: # sequence(:email) { |n| "person#{n}@example.com" } # # factory :user do # email { FactoryBot.generate(:email) } # end # # Except that no globally available sequence will be defined. def sequence(name, *args, &block) options = args.extract_options! options[:uri_paths] = @definition.uri_manager.to_a args << options new_sequence = Sequence.new(name, *args, &block) registered_sequence = __fetch_or_register_sequence(new_sequence) add_attribute(name) { increment_sequence(registered_sequence) } end # Adds an attribute that builds an association. The associated instance will # be built using the same build strategy as the parent instance. # # Example: # factory :user do # name 'Joey' # end # # factory :post do # association :author, factory: :user # end # # Arguments: # * name: +Symbol+ # The name of this attribute. # * options: +Hash+ # # Options: # * factory: +Symbol+ or +String+ # The name of the factory to use when building the associated instance. # If no name is given, the name of the attribute is assumed to be the # name of the factory. For example, a "user" association will by # default use the "user" factory. def association(name, *options) if block_given? raise AssociationDefinitionError.new( "Unexpected block passed to '#{name}' association " \ "in '#{@definition.name}' factory" ) else declaration = Declaration::Association.new(name, *options) @definition.declare_attribute(declaration) end end def to_create(&block) @definition.to_create(&block) end def skip_create @definition.skip_create end def factory(name, options = {}, &block) child_factories << [name, options, block] end def trait(name, &block) @definition.define_trait(Trait.new(name, uri_paths: @definition.uri_manager.to_a, &block)) end # Creates traits for enumerable values. # # Example: # factory :task do # traits_for_enum :status, [:started, :finished] # end # # Equivalent to: # factory :task do # trait :started do # status { :started } # end # # trait :finished do # status { :finished } # end # end # # Example: # factory :task do # traits_for_enum :status, {started: 1, finished: 2} # end # # Example: # class Task # def statuses # {started: 1, finished: 2} # end # end # # factory :task do # traits_for_enum :status # end # # Both equivalent to: # factory :task do # trait :started do # status { 1 } # end # # trait :finished do # status { 2 } # end # end # # # Arguments: # attribute_name: +Symbol+ or +String+ # the name of the attribute these traits will set the value of # values: +Array+, +Hash+, or other +Enumerable+ # An array of trait names, or a mapping of trait names to values for # those traits. When this argument is not provided, factory_bot will # attempt to get the values by calling the pluralized `attribute_name` # class method. def traits_for_enum(attribute_name, values = nil) @definition.register_enum(Enum.new(attribute_name, values)) end def initialize_with(&block) @definition.define_constructor(&block) end private def __declare_attribute__(name, block) if block.nil? declaration = Declaration::Implicit.new(name, @definition, @ignore) @definition.declare_attribute(declaration) else add_attribute(name, &block) end end def __valid_association_options?(options) options.respond_to?(:has_key?) && options.has_key?(:factory) end ## # If the inline sequence has already been registered by a parent, # return that one, otherwise register and return the given sequence # def __fetch_or_register_sequence(sequence) FactoryBot::Sequence.find_by_uri(sequence.uri_manager.first) || FactoryBot::Internal.register_inline_sequence(sequence) end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/trait.rb
lib/factory_bot/trait.rb
module FactoryBot # @api private class Trait attr_reader :name, :uid, :definition delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, :callbacks, :attributes, :klass, :klass=, to: :@definition def initialize(name, **options, &block) @name = name.to_s @block = block @uri_manager = FactoryBot::UriManager.new(names, paths: options[:uri_paths]) @definition = Definition.new(@name, uri_manager: @uri_manager) proxy = FactoryBot::DefinitionProxy.new(@definition) if block proxy.instance_eval(&@block) end end def clone Trait.new(name, uri_paths: definition.uri_manager.paths, &block) end def names [@name] end def ==(other) name == other.name && block == other.block end protected attr_reader :block end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false
thoughtbot/factory_bot
https://github.com/thoughtbot/factory_bot/blob/5115775355323252da65f323f6c10b91f2130d48/lib/factory_bot/declaration_list.rb
lib/factory_bot/declaration_list.rb
module FactoryBot # @api private class DeclarationList include Enumerable def initialize(name = nil) @declarations = [] @name = name @overridable = false end def declare_attribute(declaration) delete_declaration(declaration) if overridable? @declarations << declaration declaration end def overridable @overridable = true end def attributes @attributes ||= AttributeList.new(@name).tap do |list| to_attributes.each do |attribute| list.define_attribute(attribute) end end end def each(&block) @declarations.each(&block) end private def delete_declaration(declaration) @declarations.delete_if { |decl| decl.name == declaration.name } end def to_attributes @declarations.reduce([]) { |result, declaration| result + declaration.to_attributes } end def overridable? @overridable end end end
ruby
MIT
5115775355323252da65f323f6c10b91f2130d48
2026-01-04T15:39:01.421901Z
false