### Install Dependencies with Bundler Source: https://www.rubydoc.info/gems/factory_bot/file/CONTRIBUTING Installs all the necessary project dependencies using the Bundler gem. This is a prerequisite for running any other commands. ```bash bundle install ``` -------------------------------- ### Install factory_bot Gem Manually Source: https://www.rubydoc.info/gems/factory_bot/file/README This command installs the factory_bot gem directly from your shell, useful for global installation or when not using Bundler. ```bash gem install factory_bot ``` -------------------------------- ### Association Overrides and Building Objects: Ruby Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Provides an example of defining associations and then building objects, demonstrating how associated objects are handled. ```Ruby FactoryBot.define do factory :author do name { 'Taylor' } end factory :post do author end end eunji = build(:author, name: 'Eunji') post = build(:post, author: eunji) ``` -------------------------------- ### Format Code with Standard Source: https://www.rubydoc.info/gems/factory_bot/file/CONTRIBUTING Automatically formats the project's code according to the 'standard' style guide. This ensures consistent code style across the project. ```bash bundle exec rake standard:fix ``` -------------------------------- ### Creating a Custom JSON Build Strategy for Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Provides an example of creating a custom Factory Bot strategy that builds a JSON representation of a model. It composes the default `:create` strategy and adds JSON conversion. ```ruby class JsonStrategy def initialize @strategy = FactoryBot.strategy_by_name(:create).new end delegate :association, to: :@strategy def result(evaluation) @strategy.result(evaluation).to_json end def to_sym :json end end ``` -------------------------------- ### Example Rake Task for FactoryBot Linting Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED An example Rake task for linting FactoryBot factories within a Rails application, ensuring factories are valid before tests run. It uses a transaction to roll back database changes. ```ruby # lib/tasks/factory_bot.rake namespace :factory_bot do desc "Verify that all FactoryBot factories are valid" task lint: :environment do if Rails.env.test? conn = ActiveRecord::Base.connection conn.transaction do FactoryBot.lint raise ActiveRecord::Rollback end else system("bundle exec rake factory_bot:lint RAILS_ENV='test'") fail if $?.exitstatus.nonzero? end end end ``` -------------------------------- ### Lint Factories with FactoryBot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Provides examples of using `FactoryBot.lint` to check the validity of all defined factories. It covers basic linting, selective linting, linting traits, and using different strategies and verbosity levels. ```ruby FactoryBot.lint factories_to_lint = FactoryBot.factories.reject do |factory| factory.name =~ /^old_/ end FactoryBot.lint factories_to_lint FactoryBot.lint traits: true FactoryBot.lint factories_to_lint, traits: true FactoryBot.lint strategy: :build FactoryBot.lint verbose: true ``` -------------------------------- ### Install factory_bot Gem with Bundler Source: https://www.rubydoc.info/gems/factory_bot/file/README This command adds the factory_bot gem to your project's Gemfile using Bundler, ensuring proper dependency management. ```ruby bundle add factory_bot ``` -------------------------------- ### Define Factories Inline Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED This Ruby code illustrates how to define factories directly within your code using Factory Bot's `define` block. It includes an example of a 'user' factory with attributes. ```ruby require 'factory_bot' FactoryBot.define do factory :user do name { 'John Doe' } date_of_birth { 21.years.ago } end end ``` -------------------------------- ### Set Initial Value for Sequences in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Shows how to override the default starting value of a sequence, allowing for custom initial values or sequences that begin from a specific number or character. ```ruby factory :user do sequence(:email, 1000) { |n| "person#{n}@example.com" } end ``` -------------------------------- ### Get FactoryBot Strategies Registry Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the registry for strategies used in FactoryBot. This is a private API method. ```ruby def strategies @strategies end ``` -------------------------------- ### Require Factory Bot Gem Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED This snippet shows the basic Ruby code required to include the Factory Bot gem in your project. Ensure the gem is installed if not using Bundler. ```ruby require 'factory_bot' ``` -------------------------------- ### Define Single Callback Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Factory Bot allows defining callbacks that execute at specific points during the factory lifecycle (build, create, stub). This example shows an `after(:build)` callback. ```ruby # Define a factory that calls the generate_hashed_password method after it is built factory :user do after(:build) { |user| generate_hashed_password(user) } end ``` -------------------------------- ### Get FactoryBot Callback Names Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the set of callback names configured for FactoryBot. This is a private API method. ```ruby def callback_names @callback_names end ``` -------------------------------- ### RSpec Configuration for Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Configures RSpec to use Factory Bot's syntax methods. This setup is crucial for integrating Factory Bot seamlessly within RSpec test suites, especially in Rails applications. ```ruby RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end ``` -------------------------------- ### Monitor Factory Execution Time with ActiveSupport::Notifications Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Provides an example of using `ActiveSupport::Notifications` to track the execution time of Factory Bot factories. It subscribes to the 'factory_bot.run_factory' event and logs factories that exceed a 0.5-second execution threshold. ```Ruby ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload| execution_time_in_seconds = finish - start if execution_time_in_seconds >= 0.5 $stderr.puts "Slow factory: #{payload[:name]} using strategy #{payload[:strategy]}" end end ``` -------------------------------- ### Factory Bot Build Strategies Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Explains and demonstrates the different build strategies provided by Factory Bot: `build`, `create`, `attributes_for`, and `build_stubbed`. Also shows how to pass blocks to these methods for further customization. ```ruby # Returns a User instance that's not saved user = build(:user) # Returns a saved User instance user = create(:user) # Returns a hash of attributes that can be used to build a User instance attrs = attributes_for(:user) # Integrates with Ruby 3.0's support for pattern matching assignment attributes_for(:user) => {email:, name:, **attrs} # Returns an object with all defined attributes stubbed out stub = build_stubbed(:user) # Passing a block to any of the methods above will yield the return object create(:user) do |user| user.posts.create(attributes_for(:post)) end ``` -------------------------------- ### FactoryBot: Build single factory Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods Demonstrates the basic usage of building a single factory with optional attribute overrides and traits. It shows how to instantiate an object defined by a factory. ```ruby build(:completed_order) create(:post) do |post| create(:comment, post: post) end attributes_for(:post, title: "I love Ruby!") build_stubbed(:user, :admin, :male, name: "John Doe") ``` -------------------------------- ### Override Factory Persistence with to_create Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Shows how to customize the persistence method for Factory Bot objects. The `to_create` method can be defined on a factory to specify how an instance should be persisted, for example, using `instance.persist!`. It also covers disabling persistence entirely with `skip_create` and setting a global `to_create` within a `FactoryBot.define` block. ```Ruby factory :different_orm_model do to_create { |instance| instance.persist! } end ``` ```Ruby factory :user_without_database do skip_create end ``` ```Ruby FactoryBot.define do to_create { |instance| instance.persist! } factory :user do name { "John Doe" } end end ``` -------------------------------- ### Get Factory Class Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Retrieves the associated class for this factory definition. This is a private attribute. ```ruby def klass @klass end ``` -------------------------------- ### FactoryBot Strategy Methods Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods This section details the core methods for interacting with FactoryBot factories, including building, creating, and generating attributes. ```APIDOC ## POST /api/factories/attributes_for ### Description Generates a hash of attributes for a registered factory by name. ### Method POST ### Endpoint /api/factories/attributes_for ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to use. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user", "traits_and_overrides": [ "admin", {"name": "John Doe"} ] } ``` ### Response #### Success Response (200) - **attributes** (Hash) - A hash of attributes for the factory. #### Response Example ```json { "attributes": { "name": "John Doe", "email": "john.doe@example.com" } } ``` ``` ```APIDOC ## POST /api/factories/attributes_for_list ### Description Generates an array of attribute hashes for a registered factory by name. ### Method POST ### Endpoint /api/factories/attributes_for_list ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to use. - **amount** (integer) - Required - The number of attribute sets to generate. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "post", "amount": 3, "traits_and_overrides": [ {"title": "I love Ruby!"} ] } ``` ### Response #### Success Response (200) - **attributes_list** (Array) - An array of attribute hashes for the factory. #### Response Example ```json { "attributes_list": [ {"title": "I love Ruby!"}, {"title": "I love Ruby!"}, {"title": "I love Ruby!"} ] } ``` ``` ```APIDOC ## POST /api/factories/attributes_for_pair ### Description Generates a pair of attribute hashes for a registered factory by name. ### Method POST ### Endpoint /api/factories/attributes_for_pair ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to use. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user" } ``` ### Response #### Success Response (200) - **attributes_pair** (Array) - A pair of attribute hashes for the factory. #### Response Example ```json { "attributes_pair": [ {"email": "user1@example.com"}, {"email": "user2@example.com"} ] } ``` ``` ```APIDOC ## POST /api/factories/build ### Description Builds a registered factory by name. This creates an instance of the object associated with the factory but does not save it to the database. ### Method POST ### Endpoint /api/factories/build ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides to apply during the build process. ### Request Example ```json { "name": "order", "traits_and_overrides": [ "completed", {"total_amount": 100} ] } ``` ### Response #### Success Response (200) - **built_object** (Object) - The instantiated object defined by the factory. #### Response Example ```json { "built_object": { "id": 1, "status": "completed", "total_amount": 100 } } ``` ``` ```APIDOC ## POST /api/factories/build_list ### Description Builds a list of registered factories by name. This creates multiple instances of the objects associated with the factory but does not save them to the database. ### Method POST ### Endpoint /api/factories/build_list ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. - **amount** (integer) - Required - The number of instances to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides to apply during the build process. ### Request Example ```json { "name": "product", "amount": 5, "traits_and_overrides": [ {"price": 50} ] } ``` ### Response #### Success Response (200) - **built_list** (Array) - An array of instantiated objects defined by the factory. #### Response Example ```json { "built_list": [ {"id": 1, "price": 50}, {"id": 2, "price": 50}, {"id": 3, "price": 50}, {"id": 4, "price": 50}, {"id": 5, "price": 50} ] } ``` ``` ```APIDOC ## POST /api/factories/build_pair ### Description Builds a pair of registered factories by name. This creates two instances of the objects associated with the factory but does not save them to the database. ### Method POST ### Endpoint /api/factories/build_pair ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides to apply during the build process. ### Request Example ```json { "name": "user" } ``` ### Response #### Success Response (200) - **built_pair** (Array) - A pair of instantiated objects defined by the factory. #### Response Example ```json { "built_pair": [ {"id": 1, "name": "User One"}, {"id": 2, "name": "User Two"} ] } ``` ``` ```APIDOC ## POST /api/factories/build_stubbed ### Description Builds a stubbed registered factory by name. This creates a stubbed instance of the object associated with the factory. ### Method POST ### Endpoint /api/factories/build_stubbed ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user", "traits_and_overrides": [ "male", {"name": "John Doe"} ] } ``` ### Response #### Success Response (200) - **built_stubbed_object** (Object) - The stubbed instantiated object defined by the factory. #### Response Example ```json { "built_stubbed_object": { "id": 1, "name": "John Doe", "gender": "male" } } ``` ``` ```APIDOC ## POST /api/factories/build_stubbed_list ### Description Builds a stubbed list of registered factories by name. ### Method POST ### Endpoint /api/factories/build_stubbed_list ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. - **amount** (integer) - Required - The number of stubbed instances to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user", "amount": 15, "traits_and_overrides": [ "admin", "male", {"name": "John Doe"} ] } ``` ### Response #### Success Response (200) - **built_stubbed_list** (Array) - An array of stubbed instantiated objects. #### Response Example ```json { "built_stubbed_list": [ {"id": 1, "name": "John Doe", "gender": "male", "role": "admin"}, {"id": 2, "name": "John Doe", "gender": "male", "role": "admin"}, ... ] } ``` ``` ```APIDOC ## POST /api/factories/build_stubbed_pair ### Description Builds a stubbed pair of registered factories by name. ### Method POST ### Endpoint /api/factories/build_stubbed_pair ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to build. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user" } ``` ### Response #### Success Response (200) - **built_stubbed_pair** (Array) - A pair of stubbed instantiated objects. #### Response Example ```json { "built_stubbed_pair": [ {"id": 1, "name": "User One"}, {"id": 2, "name": "User Two"} ] } ``` ``` ```APIDOC ## POST /api/factories/create ### Description Creates a registered factory by name. This creates and saves an instance of the object associated with the factory, typically to a database. ### Method POST ### Endpoint /api/factories/create ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to create. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides to apply during the creation process. ### Request Example ```json { "name": "post", "traits_and_overrides": [ {"title": "I love Ruby!"} ] } ``` ### Response #### Success Response (200) - **created_object** (Object) - The created object defined by the factory. #### Response Example ```json { "created_object": { "id": 1, "title": "I love Ruby!", "created_at": "2023-10-27T10:00:00Z" } } ``` ``` ```APIDOC ## POST /api/factories/create_list ### Description Creates a list of registered factories by name. This creates and saves multiple instances of the objects associated with the factory. ### Method POST ### Endpoint /api/factories/create_list ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to create. - **amount** (integer) - Required - The number of instances to create. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides to apply during the creation process. ### Request Example ```json { "name": "comment", "amount": 3, "traits_and_overrides": [ {"body": "Great post!"} ] } ``` ### Response #### Success Response (200) - **created_list** (Array) - An array of created objects defined by the factory. #### Response Example ```json { "created_list": [ {"id": 1, "body": "Great post!"}, {"id": 2, "body": "Great post!"}, {"id": 3, "body": "Great post!"} ] } ``` ``` ```APIDOC ## POST /api/factories/create_pair ### Description Creates a pair of registered factories by name. This creates and saves two instances of the objects associated with the factory. ### Method POST ### Endpoint /api/factories/create_pair ### Parameters #### Path Parameters - **name** (string) - Required - The name of the factory to create. #### Query Parameters - **traits_and_overrides** (string) - Optional - Traits and attribute overrides. ### Request Example ```json { "name": "user" } ``` ### Response #### Success Response (200) - **created_pair** (Array) - A pair of created objects defined by the factory. #### Response Example ```json { "created_pair": [ {"id": 1, "name": "User One"}, {"id": 2, "name": "User Two"} ] } ``` ``` ```APIDOC ## GET /api/sequences/generate ### Description Generates and returns the next value in a global or factory sequence. ### Method GET ### Endpoint /api/sequences/generate ### Parameters #### Path Parameters - **uri_parts** (string) - Required - Parts of the URI defining the sequence. #### Query Parameters - **scope** (string) - Optional - The scope of the sequence. ### Request Example ```json { "uri_parts": ["global", "counter"], "scope": "default" } ``` ### Response #### Success Response (200) - **next_value** (Object) - The next value in the sequence. #### Response Example ```json { "next_value": 1 } ``` ``` ```APIDOC ## GET /api/sequences/generate_list ### Description Generates and returns a list of values in a global or factory sequence. ### Method GET ### Endpoint /api/sequences/generate_list ### Parameters #### Path Parameters - **uri_parts** (string) - Required - Parts of the URI defining the sequence. - **count** (integer) - Required - The number of values to generate. #### Query Parameters - **scope** (string) - Optional - The scope of the sequence. ### Request Example ```json { "uri_parts": ["global", "counter"], "count": 5, "scope": "default" } ``` ### Response #### Success Response (200) - **values_list** (Object) - A list of values from the sequence. #### Response Example ```json { "values_list": [1, 2, 3, 4, 5] } ``` ``` -------------------------------- ### Get Registered Enums Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Returns a list of registered enumerations for this factory. This is a private, read-only attribute. ```ruby def registered_enums @registered_enums end ``` -------------------------------- ### Manage Attribute Precedence with Factory Bot Traits Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Illustrates how Factory Bot handles attribute precedence when traits define the same attributes. The latest defined attribute takes precedence, as shown in the 'active_admin' and 'inactive_admin' examples. ```ruby factory :user do name { "Friendly User" } login { name } trait :active do name { "John Doe" } status { :active } login { "#{name} (active)" } end trait :inactive do name { "Jane Doe" } status { :inactive } login { "#{name} (inactive)" } end trait :admin do admin { true } login { "admin-#{name}" } end factory :active_admin, traits: [:active, :admin] # login will be "admin-John Doe" factory :inactive_admin, traits: [:admin, :inactive] # login will be "Jane Doe (inactive)" end ``` -------------------------------- ### Get URI Manager Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Returns the URI manager associated with this factory definition. This is a private, read-only attribute. ```ruby def uri_manager @uri_manager end ``` -------------------------------- ### Get Defined Traits Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Returns a set of defined traits for this factory. This is a private attribute used internally. ```ruby def defined_traits @defined_traits end ``` -------------------------------- ### Build or Create Multiple Records with FactoryBot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Illustrates how to build or create multiple instances of a factory at once using `build_list` and `create_list`. You can also specify attributes for all records or use a block to set attributes individually. ```ruby built_users = build_list(:user, 25) created_users = create_list(:user, 25) twenty_year_olds = build_list(:user, 25, date_of_birth: 20.years.ago) twenty_somethings = build_list(:user, 10) do |user, i| user.date_of_birth = (20 + i).years.ago end twenty_somethings = create_list(:user, 10) do |user, i| user.date_of_birth = (20 + i).years.ago user.save! end ``` -------------------------------- ### Get the next value from EnumeratorAdapter Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Sequence/EnumeratorAdapter Advances the EnumeratorAdapter to its next value. This is a private API method. ```Ruby def next @value = value.next end ``` -------------------------------- ### Initialize FactoryBot::Sequence Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Sequence%3Ainitialize Initializes a new FactoryBot::Sequence object. It accepts a name, optional arguments (including options like :aliases and :uri_paths), and a block. It sets up internal attributes like name, proc, aliases, and a UriManager, and initializes the sequence value. ```Ruby 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 ``` -------------------------------- ### Define Factory Bot Factories with Associations Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Shows a Factory Bot definition for a 'Location' model with an association to 'LocationGroup'. This example is used to illustrate potential `ActiveRecord::AssociationTypeMismatch` errors when using Rails preloaders with Factory Bot. ```Ruby FactoryBot.define do factory :united_states, class: "Location" do name { 'United States' } association :location_group, factory: :north_america end factory :north_america, class: "LocationGroup" do name { 'North America' } end end ``` -------------------------------- ### Get FactoryBot::Attribute Name Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Attribute Returns the name of the attribute. This is a private readonly instance attribute accessor. ```Ruby def name @name end ``` -------------------------------- ### Global Initialization Override in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Demonstrates how to set a default `initialize_with` behavior for all factories within a `FactoryBot.define` block, simplifying configuration for multiple factories. ```ruby FactoryBot.define do initialize_with { new("Awesome first argument") } end ``` -------------------------------- ### Get Factory Declarations Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Returns the list of declarations associated with this factory definition. This is a private attribute and is intended for internal use. ```ruby def declarations @declarations end ``` -------------------------------- ### Minitest Integration with Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Includes Factory Bot's syntax methods into Minitest::Unit::TestCase, enabling the use of Factory Bot methods within Minitest unit tests. ```ruby class Minitest::Unit::TestCase include FactoryBot::Syntax::Methods end ``` -------------------------------- ### Get FactoryBot Trait Names Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Trait Returns an array containing the name of the FactoryBot::Trait. This is a private method. ```Ruby def names [@name] end ``` -------------------------------- ### FactoryBot::Evaluation Constructor Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Evaluation Initializes a new instance of the FactoryBot::Evaluation class. It takes the evaluator, attribute assigner, creation method, and an observer as arguments. ```Ruby def initialize(evaluator, attribute_assigner, to_create, observer) @evaluator = evaluator @attribute_assigner = attribute_assigner @to_create = to_create @observer = observer end ``` -------------------------------- ### FactoryBot::Callback initialize Method Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Callback Initializes a new instance of FactoryBot::Callback with a name and a block. The name is stored as a symbol. This method is essential for setting up callbacks. ```ruby def initialize(name, block) @name = name.to_sym @block = block end ``` -------------------------------- ### Build Stubbed and Paired Records with FactoryBot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Demonstrates using `build_stubbed_list` for stubbed instances and `build_pair`/`create_pair` for creating two records at a time. ```ruby stubbed_users = build_stubbed_list(:user, 25) # array of stubbed users built_users = build_pair(:user) # array of two built users created_users = create_pair(:user) # array of two created users ``` -------------------------------- ### Get FactoryBot Factories Registry Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the registry for factories, which prevents duplicate entries. This is a private API method. ```ruby def factories @factories end ``` -------------------------------- ### Get FactoryBot::Attribute Ignored Status Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Attribute Returns the ignored status of the attribute. This is a private readonly instance attribute accessor. ```Ruby def ignored @ignored end ``` -------------------------------- ### Instantiate Factories with Traits Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Explains how to pass traits as a list of symbols when constructing an instance from Factory Bot using methods like `create`. This allows applying multiple traits and overriding attributes. ```ruby factory :user do name { "Friendly User" } trait :active do name { "John Doe" } status { :active } end trait :admin do admin { true } end end # creates an admin user with :active status and name "Jon Snow" create(:user, :admin, :active, name: "Jon Snow") ``` -------------------------------- ### Custom Initialization with Class Methods in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Shows how to use `initialize_with` in Factory Bot to call a specific class method for object instantiation, rather than the default `new` method. This allows for more complex object creation logic. ```ruby factory :user do name { "John Doe" } initialize_with { User.build_with_name(name) } end ``` -------------------------------- ### Get names of defined traits in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Returns an array of names for all traits that have been defined for this factory. This method is part of the private API. ```ruby # File 'lib/factory_bot/definition.rb', line 99 def defined_traits_names @defined_traits.map(&:name) end ``` -------------------------------- ### FactoryBot::FactoryRunner Constructor Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/FactoryRunner Initializes a new instance of FactoryRunner. It takes the factory name, strategy, and traits/overrides as arguments, setting up internal instance variables for later use. ```ruby def initialize(name, strategy, traits_and_overrides) @name = name @strategy = strategy @overrides = traits_and_overrides.extract_options! @traits = traits_and_overrides end ``` -------------------------------- ### Get FactoryBot Traits Registry Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the registry for traits, which prevents duplicate trait definitions. This is a private API method. ```ruby def traits @traits end ``` -------------------------------- ### Get FactoryBot Sequences Registry Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the registry for sequences, ensuring no duplicate sequence names. This is a private API method. ```ruby def sequences @sequences end ``` -------------------------------- ### FactoryBot::Factory#initialize Ruby Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Factory Initializes a new FactoryBot::Factory instance. It sets up the factory's name, class, aliases, and definition. This method is part of the private API. ```ruby 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 ``` -------------------------------- ### FactoryBot: Build multiple factories Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods Illustrates how to build multiple instances of a factory at once using methods like `build_list`, `create_list`, and `attributes_for_list`. This is useful for generating collections of objects with potential overrides. ```ruby build_list(:completed_order, 2) create_list(:completed_order, 2) attributes_for_list(:post, 4, title: "I love Ruby!") build_stubbed_list(:user, 15, :admin, :male, name: "John Doe") ``` -------------------------------- ### Get FactoryBot Trait UID Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Trait Returns the unique identifier (UID) of the FactoryBot::Trait. This is a private method intended for internal use. ```Ruby def uid @uid end ``` -------------------------------- ### minitest-rails Integration with Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Includes Factory Bot's syntax methods in ActiveSupport::TestCase, which is the base class for most tests in a minitest-rails application. This makes Factory Bot methods readily available. ```ruby class ActiveSupport::TestCase include FactoryBot::Syntax::Methods end ``` -------------------------------- ### Get FactoryBot Inline Sequences Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Returns the list of inline sequences defined within the FactoryBot configuration. This is a private API method. ```ruby def inline_sequences @inline_sequences end ``` -------------------------------- ### Get FactoryBot::Declaration Name Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Declaration Accessor for the 'name' instance attribute of the FactoryBot::Declaration class. This method is read-only and part of the private API. ```Ruby # File 'lib/factory_bot/declaration.rb', line 8 def name @name end ``` -------------------------------- ### Custom User Initialization with Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Demonstrates how to override the default initialization process in Factory Bot to use a custom `initialize` method for a Ruby class. This is useful for objects that require arguments during instantiation. ```ruby class User attr_accessor :name, :email def initialize(name) @name = name end end sequence(:email) { |n| "person#{n}@example.com" } factory :user do name { "Jane Doe" } email initialize_with { new(name) } end build(:user).name # Jane Doe ``` -------------------------------- ### Create List (Ruby) Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods Creates and returns an array of objects defined by the factory. It takes the factory name, the desired amount, and optional traits or overrides. ```ruby def create_list(name, amount, *traits_and_overrides, &block) # ... (implementation not shown) end ``` -------------------------------- ### Create a Child Factory Inheriting from User Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Demonstrates how to create a new factory, 'application_user', that inherits from the 'user' factory and adds additional attributes. ```ruby FactoryBot.define do factory :application_user, parent: :user do full_name { "Jane Doe" } date_of_birth { 21.years.ago } health { 90 } end end ``` -------------------------------- ### Define and Generate Global Sequences with Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Shows how to define a global sequence for generating unique values, such as email addresses, using a counter. It illustrates defining the sequence and then generating values from it. ```ruby # Defines a new sequence FactoryBot.define do sequence :email do |n| "person#{n}@example.com" end end generate :email # => "person1@example.com" generate :email # => "person2@example.com" ``` -------------------------------- ### Get Factory Location in FactoryBot::Linter::FactoryError Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Linter/FactoryError Returns the name of the factory associated with this error. This method is used to provide context about the factory causing the linting error. ```ruby def location @factory.name end ``` -------------------------------- ### Initialize FactoryBot::Decorator::NewConstructor Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Decorator/NewConstructor Initializes a new instance of FactoryBot::Decorator::NewConstructor. It takes a component and a build_class as arguments and calls the superclass constructor with the component. ```ruby def initialize(component, build_class) super(component) @build_class = build_class end ``` -------------------------------- ### Registering a Custom Strategy in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Demonstrates how to register a custom strategy (e.g., `:json`) with Factory Bot, allowing it to be used like built-in strategies. ```ruby FactoryBot.register_strategy(:json, JsonStrategy) ``` -------------------------------- ### Get Factory Name from Association Attribute in FactoryBot Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Attribute/Association Retrieves the factory name associated with this attribute. This is a readonly attribute and is part of the private API, meaning its usage is discouraged. ```Ruby # File 'lib/factory_bot/attribute/association.rb', line 5 def factory @factory end ``` -------------------------------- ### Get Attribute Names from FactoryBot::AttributeList Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/AttributeList Returns an array of names for all attributes currently in the list. This method maps over the attributes and extracts their names. It's a private API method. ```Ruby def names map(&:name) end ``` -------------------------------- ### Define Inline Sequences with Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Explains how to define a sequence directly within a factory definition, making it specific to that factory's usage. It covers both standard and abbreviated syntax for inline sequences. ```ruby factory :user do sequence(:email) { |n| "person#{n}@example.com" } end ``` ```ruby factory :user do sequence(:email) { "person#{_1}@example.com" } end ``` -------------------------------- ### FactoryBot DefinitionProxy: Initialize Constructor Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/DefinitionProxy Initializes a new instance of the DefinitionProxy class. It sets up internal attributes like @definition, @ignore, and @child_factories, preparing the proxy for attribute declarations. ```Ruby # File 'lib/factory_bot/definition_proxy.rb', line 26 def initialize(definition, ignore = false) @definition = definition @ignore = ignore @child_factories = [] end ``` -------------------------------- ### Initialize FactoryBot::Registry Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Registry Initializes a new instance of FactoryBot::Registry with a given name. It sets up an internal hash-like structure to store items, using ActiveSupport::HashWithIndifferentAccess for flexible key access. ```ruby def initialize(name) @name = name @items = ActiveSupport::HashWithIndifferentAccess.new end ``` -------------------------------- ### FactoryBot::Definition#to_create Method Implementation Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition%3Ato_create This Ruby code defines the `to_create` method for the `FactoryBot::Definition` class. It allows setting a block for a custom creation strategy or retrieving the currently defined strategy. It is part of the FactoryBot gem. ```ruby def to_create(&block) if block @to_create = block else aggregate_from_traits_and_self(:to_create) { @to_create }.last end end ``` -------------------------------- ### Get Location of FactoryTraitError Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Linter/FactoryTraitError Returns the location of the factory trait error. This method formats a string combining the factory's name and the trait name to pinpoint the error's origin. ```Ruby def location "#{@factory.name}+#{@trait_name}" end ``` -------------------------------- ### Get Non-Ignored Attributes from FactoryBot::AttributeList Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/AttributeList Returns a new AttributeList containing only the non-ignored attributes from the current list. This filters out any attributes marked as ignored. It's a private API method. ```Ruby def non_ignored AttributeList.new(@name, reject(&:ignored)) end ``` -------------------------------- ### Get Associations from FactoryBot::AttributeList Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/AttributeList Returns a new AttributeList containing only the associated attributes from the current list. This is achieved by selecting attributes that are marked as associations. It's a private API method. ```Ruby def associations AttributeList.new(@name, select(&:association?)) end ``` -------------------------------- ### FactoryBot Create Strategy: Result Method Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Strategy/Create Handles the creation process, including notifications before and after building and creating the object. It ensures callbacks are executed correctly during the object lifecycle. ```ruby # File 'lib/factory_bot/strategy/create.rb', line 8 def result(evaluation) evaluation.notify(:before_build, nil) evaluation.object.tap do |instance| evaluation.notify(:after_build, instance) evaluation.notify(:before_create, instance) evaluation.create(instance) evaluation.notify(:after_create, instance) end end ``` -------------------------------- ### FactoryBot generate method implementation Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods%3Agenerate This Ruby code defines the 'generate' method within the FactoryBot::Syntax::Methods class. It builds a URI from the provided parts, finds the corresponding sequence, and increments it within the given scope. If the sequence is not found, it raises a KeyError. ```Ruby def generate(*uri_parts, scope: nil) uri = FactoryBot::UriManager.build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || raise(KeyError, "Sequence not registered: #{FactoryBot::UriManager.build_uri(uri_parts)}") increment_sequence(sequence, scope: scope) end ``` -------------------------------- ### Get Ignored Attributes from FactoryBot::AttributeList Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/AttributeList Returns a new AttributeList containing only the ignored attributes from the current list. This is done by filtering attributes marked as ignored. It's a private API method. ```Ruby def ignored AttributeList.new(@name, select(&:ignored)) end ``` -------------------------------- ### Initialize CallbacksObserver Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/CallbacksObserver Initializes a new instance of FactoryBot::CallbacksObserver. This method takes callbacks and an evaluator as arguments and sets up internal state for tracking completed callbacks. It is part of a private API. ```Ruby def initialize(callbacks, evaluator) @callbacks = callbacks @evaluator = evaluator @completed = [] end ``` -------------------------------- ### FactoryBot::Evaluation create Method Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Evaluation Creates an instance using the provided result_instance. It dynamically calls the 'to_create' method based on its arity (number of arguments it accepts). ```Ruby def create(result_instance) case @to_create.arity when 2 then @to_create[result_instance, @evaluator] else @to_create[result_instance] end end ``` -------------------------------- ### Initialize FactoryBot::StrategyCalculator Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/StrategyCalculator%3Ainitialize Initializes a new instance of StrategyCalculator with a given name or object. This method is part of the private API and should be used with caution. ```ruby def initialize(name_or_object) @name_or_object = name_or_object end ``` -------------------------------- ### Get the factory constructor block in Factory Bot Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Definition Retrieves the constructor block defined for the factory. It aggregates the constructor from traits and the factory definition, returning the last one found. This method is part of the private API. ```ruby # File 'lib/factory_bot/definition.rb', line 42 def constructor aggregate_from_traits_and_self(:constructor) { @constructor }.last end ``` -------------------------------- ### RSpec Configuration for Non-Rails Projects Source: https://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED Sets up Factory Bot for RSpec in projects not using Rails. It includes the syntax methods and a before(:suite) hook to find factory definitions, ensuring factories are available before tests run. ```ruby RSpec.configure do |config| config.include FactoryBot::Syntax::Methods config.before(:suite) do FactoryBot.find_definitions end end ``` -------------------------------- ### Initialize FactoryBot Configuration Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Configuration Initializes the FactoryBot configuration with various registries for factories, sequences, traits, and strategies. It also sets up default callbacks and definitions. This method is part of the private API. ```ruby 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 ``` -------------------------------- ### Get Strategy Object - Ruby Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/StrategyCalculator%3Astrategy This Ruby method determines and returns the strategy object based on whether the internal strategy name is an object or needs conversion. It's a private API method. ```ruby def strategy if strategy_is_object? @name_or_object else strategy_name_to_object end end ``` -------------------------------- ### FactoryBot: Build Single Factory (Ruby) Source: https://www.rubydoc.info/gems/factory_bot/FactoryBot/Syntax/Methods Builds a registered factory by name, returning an instantiated object. This is a core method for creating model instances with FactoryBot. ```ruby # File 'lib/factory_bot/syntax/methods.rb', line 33 build(:completed_order) ```