pax_global_header00006660000000000000000000000064140452623160014515gustar00rootroot0000000000000052 comment=d07fa850f3aec96393db446ed1a533d005c73e57 factory_bot-6.2.0/000077500000000000000000000000001404526231600140355ustar00rootroot00000000000000factory_bot-6.2.0/.github/000077500000000000000000000000001404526231600153755ustar00rootroot00000000000000factory_bot-6.2.0/.github/ISSUE_TEMPLATE/000077500000000000000000000000001404526231600175605ustar00rootroot00000000000000factory_bot-6.2.0/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000017371404526231600222620ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: '' labels: 'bug' assignees: '' --- ### Description ### Reproduction Steps ### Expected behavior ### Actual behavior ### System configuration **factory_bot version**: **rails version**: **ruby version**: factory_bot-6.2.0/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000012431404526231600233050ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: '' labels: 'feature' assignees: '' --- ### Problem this feature will solve ### Desired solution ## Alternatives considered ## Additional context factory_bot-6.2.0/.github/REPRODUCTION_SCRIPT.rb000066400000000000000000000023321404526231600207230ustar00rootroot00000000000000require "bundler/inline" gemfile(true) do source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } gem "factory_bot", "~> 6.0" gem "activerecord" gem "sqlite3" end require "active_record" require "factory_bot" require "minitest/autorun" require "logger" ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Schema.define do # TODO: Update the schema to include the specific tables or columns necessary # to reproduct the bug create_table :posts, force: true do |t| t.string :body end end # TODO: Add any application specific code necessary to reproduce the bug class Post < ActiveRecord::Base end FactoryBot.define do # TODO: Write the factory definitions necessary to reproduce the bug factory :post do body { "Post body" } end end class FactoryBotTest < Minitest::Test def test_factory_bot_stuff # TODO: Write a failing test case to demonstrate what isn't working as # expected body_override = "Body override" post = FactoryBot.build(:post, body: body_override) assert_equal post.body, body_override end end # Run the tests with `ruby ` factory_bot-6.2.0/.github/workflows/000077500000000000000000000000001404526231600174325ustar00rootroot00000000000000factory_bot-6.2.0/.github/workflows/build.yml000066400000000000000000000035631404526231600212630ustar00rootroot00000000000000name: Build on: - push - pull_request jobs: build: name: Ruby ${{ matrix.ruby }} / Rails ${{ matrix.rails }} continue-on-error: ${{ matrix.allow_failure || false }} strategy: fail-fast: false matrix: ruby: - jruby-9.2.16.0 - ruby-head - "3.0" - "2.7" - "2.6" - "2.5" rails: - "5.0" - "5.1" - "5.2" - "6.0" - "6.1" - main exclude: - ruby: 2.5 rails: main - ruby: 2.6 rails: main - ruby: 3.0 rails: "5.0" - ruby: 3.0 rails: "5.1" - ruby: 3.0 rails: "5.2" - ruby: ruby-head rails: "5.0" - ruby: ruby-head rails: "5.1" - ruby: ruby-head rails: "5.2" include: # Failures permitted on latest ruby but useful for visibility - allow_failure: true ruby: ruby-head rails: "6.0" - allow_failure: true ruby: ruby-head rails: "6.1" # Failures permitted on latest rails but useful for visibility - allow_failure: true ruby: jruby-9.2.16.0 rails: main - allow_failure: true ruby: ruby-head rails: main - allow_failure: true ruby: "3.0" rails: main - allow_failure: true ruby: "2.7" rails: main runs-on: 'ubuntu-latest' env: BUNDLE_GEMFILE: gemfiles/${{ matrix.rails }}.gemfile steps: - uses: actions/checkout@v2 - uses: ruby/setup-ruby@v1 with: ruby-version: ${{ matrix.ruby }} - name: Setup project run: bundle install - name: Run test run: bundle exec rake factory_bot-6.2.0/.gitignore000066400000000000000000000002051404526231600160220ustar00rootroot00000000000000*.swp test.db factory_girl-*.gem factory_bot-*.gem doc .yardoc coverage .bundle tmp bin .rubocop-https* gemfiles/master.gemfile.lock factory_bot-6.2.0/.hound.yml000066400000000000000000000000451404526231600157520ustar00rootroot00000000000000rubocop: config_file: .rubocop.yml factory_bot-6.2.0/.rspec000066400000000000000000000000601404526231600151460ustar00rootroot00000000000000--format progress --color --require spec_helper factory_bot-6.2.0/.simplecov000066400000000000000000000001021404526231600160300ustar00rootroot00000000000000SimpleCov.start do add_filter "/spec/" add_filter "/tmp/" end factory_bot-6.2.0/.yardopts000066400000000000000000000001011404526231600156730ustar00rootroot00000000000000lib/**/*.rb - GETTING_STARTED.md CONTRIBUTING.md NAME.md LICENSE factory_bot-6.2.0/Appraisals000066400000000000000000000017701404526231600160640ustar00rootroot00000000000000appraise "5.0" do gem "activerecord", "~> 5.0.7" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", "~> 1.3.6", platforms: [:ruby] end appraise "5.1" do gem "activerecord", "~> 5.1.7" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end appraise "5.2" do gem "activerecord", "~> 5.2.3" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end appraise "6.0" do gem "activerecord", "~> 6.0.0" gem "activerecord-jdbcsqlite3-adapter", "~> 60.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end appraise "6.1" do gem "activerecord", "~> 6.1.0" gem "activerecord-jdbcsqlite3-adapter", "~> 61.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end appraise "main" do gem "activerecord", git: "https://github.com/rails/rails.git", branch: "main" gem "activerecord-jdbcsqlite3-adapter", "~> 61.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end factory_bot-6.2.0/CODE_OF_CONDUCT.md000066400000000000000000000002511404526231600166320ustar00rootroot00000000000000# Code of conduct By participating in this project, you agree to abide by the [thoughtbot code of conduct][1]. [1]: https://thoughtbot.com/open-source-code-of-conduct factory_bot-6.2.0/CONTRIBUTING.md000066400000000000000000000061541404526231600162740ustar00rootroot00000000000000# Contributing to Factory Bot We love pull requests from everyone. By participating in this project, you agree to abide by the thoughtbot [code of conduct]. [code of conduct]: https://thoughtbot.com/open-source-code-of-conduct Here are some ways *you* can contribute: * by using alpha, beta, and prerelease versions * by reporting bugs * by suggesting new features * by writing or editing documentation * by writing specifications * by writing code ( **no patch is too small** : fix typos, add comments, etc. ) * by refactoring code * by closing [issues][] * by reviewing patches [issues]: https://github.com/thoughtbot/factory_bot/issues ## Submitting an Issue * We use the [GitHub issue tracker][issues] to track bugs and features. * Before submitting a bug report or feature request, check to make sure it hasn't already been submitted. * When submitting a bug report, please include a [reproduction script] and any other details that may be necessary to reproduce the bug, including your gem version, Ruby version, and operating system. ## Cleaning up issues * Issues that have no response from the submitter will be closed after 30 days. * Issues will be closed once they're assumed to be fixed or answered. If the maintainer is wrong, it can be opened again. * If your issue is closed by mistake, please understand and explain the issue. We will happily reopen the issue. ## Submitting a Pull Request 1. [Fork][fork] the [official repository][repo]. 1. [Create a topic branch.][branch] 1. Implement your feature or bug fix. 1. Add, commit, and push your changes. 1. [Submit a pull request.][pr] ### Notes * Please add tests if you changed code. Contributions without tests won't be accepted. * If you don't know how to add tests, please put in a PR and leave a comment asking for help. We love helping! * Please don't update the Gem version. ## Setting up ```sh bundle install ``` ## Running the test suite The default rake task will run the full test suite and [standard]: ```sh bundle exec rake ``` You can also run a single group of tests (unit, spec, or feature) ```sh bundle exec rake spec:unit bundle exec rake spec:acceptance bundle exec rake features ``` To run an individual rspec test, you can provide a path and line number: ```sh bundle exec rspec spec/path/to/spec.rb:123 ``` You can run tests with a specific version of rails via [appraisal]. To run the default rake task against Rails 6, for example: ```sh bundle exec appraisal 6.0 rake ``` ## Formatting Use [standard] to automatically format your code: ```sh bundle exec rake standard:fix ``` [repo]: https://github.com/thoughtbot/factory_bot/tree/master [fork]: https://help.github.com/articles/fork-a-repo/ [branch]: https://help.github.com/articles/creating-and-deleting-branches-within-your-repository/ [pr]: https://help.github.com/articles/using-pull-requests/ [standard]: https://github.com/testdouble/standard [appraisal]: https://github.com/thoughtbot/appraisal [reproduction script]: https://github.com/thoughtbot/factory_bot/blob/master/.github/REPRODUCTION_SCRIPT.rb Inspired by https://github.com/middleman/middleman-heroku/blob/master/CONTRIBUTING.md factory_bot-6.2.0/GETTING_STARTED.md000066400000000000000000001360301404526231600166510ustar00rootroot00000000000000Getting Started =============== * [Setup](#setup) + [Update Your Gemfile](#update-your-gemfile) + [Configure your test suite](#configure-your-test-suite) - [RSpec](#rspec) - [Test::Unit](#testunit) - [Cucumber](#cucumber) - [Spinach](#spinach) - [Minitest](#minitest) - [Minitest::Spec](#minitestspec) - [minitest-rails](#minitest-rails) * [Defining factories](#defining-factories) + [Factory name and attributes](#factory-name-and-attributes) + [Specifying the class explicitly](#specifying-the-class-explicitly) + [Hash attributes](#hash-attributes) + [Best practices](#best-practices) + [Definition file paths](#definition-file-paths) + [Static Attributes](#static-attributes) * [Using factories](#using-factories) + [Build strategies](#build-strategies) + [Attribute overrides](#attribute-overrides) + [`build_stubbed` and `Marshal.dump`](#build_stubbed-and-marshaldump) * [Aliases](#aliases) * [Dependent Attributes](#dependent-attributes) * [Transient Attributes](#transient-attributes) + [With other attributes](#with-other-attributes) + [With `attributes_for`](#with-attributes_for) + [With callbacks](#with-callbacks) + [With associations](#with-associations) * [Method Name / Reserved Word Attributes](#method-name--reserved-word-attributes) * [Inheritance](#inheritance) + [Nested factories](#nested-factories) + [Assigning parent explicitly](#assigning-parent-explicitly) + [Best practices](#best-practices-1) * [Associations](#associations) + [Implicit definition](#implicit-definition) + [Explicit definition](#explicit-definition) + [Inline definition](#inline-definition) + [Specifying the factory](#specifying-the-factory) + [Overriding attributes](#overriding-attributes) + [Association overrides](#association-overrides) + [Build strategies](#build-strategies-1) + [`has_many` associations](#has_many-associations) + [`has_and_belongs_to_many` associations](#has_and_belongs_to_many-associations) + [Polymorphic associations](#polymorphic-associations) + [Interconnected associations](#interconnected-associations) * [Sequences](#sequences) + [Global sequences](#global-sequences) + [With dynamic attributes](#with-dynamic-attributes) + [As implicit attributes](#as-implicit-attributes) + [Inline sequences](#inline-sequences) + [Initial value](#initial-value) + [Without a block](#without-a-block) + [Aliases](#aliases-1) + [Rewinding](#rewinding) + [Uniqueness](#uniqueness) * [Traits](#traits) + [Defining traits](#defining-traits) + [As implicit attributes](#as-implicit-attributes-1) + [Attribute precedence](#attribute-precedence) + [In child factories](#in-child-factories) + [Using traits](#using-traits) + [With associations](#with-associations-1) + [Traits within traits](#traits-within-traits) + [With transient attributes](#with-transient-attributes) + [Enum traits](#enum-traits) * [Callbacks](#callbacks) + [Default callbacks](#default-callbacks) + [Multiple callbacks](#multiple-callbacks) + [Global callbacks](#global-callbacks) + [Symbol#to_proc](#symbolto_proc) * [Modifying factories](#modifying-factories) * [Building or Creating Multiple Records](#building-or-creating-multiple-records) * [Linting Factories](#linting-factories) * [Custom Construction](#custom-construction) * [Custom Strategies](#custom-strategies) * [Custom Callbacks](#custom-callbacks) * [Custom Methods to Persist Objects](#custom-methods-to-persist-objects) * [ActiveSupport Instrumentation](#activesupport-instrumentation) * [Rails Preloaders and RSpec](#rails-preloaders-and-rspec) * [Using Without Bundler](#using-without-bundler) Setup ----- ### Update Your Gemfile If you're using Rails: ```ruby gem "factory_bot_rails" ``` If you're *not* using Rails: ```ruby gem "factory_bot" ``` ### Configure your test suite #### RSpec If you're using Rails, add the following configuration to `spec/support/factory_bot.rb` and be sure to require that file in `rails_helper.rb`: ```ruby RSpec.configure do |config| config.include FactoryBot::Syntax::Methods end ``` If you're *not* using Rails: ```ruby RSpec.configure do |config| config.include FactoryBot::Syntax::Methods config.before(:suite) do FactoryBot.find_definitions end end ``` #### Test::Unit ```ruby class Test::Unit::TestCase include FactoryBot::Syntax::Methods end ``` #### Cucumber ```ruby # env.rb (Rails example location - RAILS_ROOT/features/support/env.rb) World(FactoryBot::Syntax::Methods) ``` #### Spinach ```ruby class Spinach::FeatureSteps include FactoryBot::Syntax::Methods end ``` #### Minitest ```ruby class Minitest::Unit::TestCase include FactoryBot::Syntax::Methods end ``` #### Minitest::Spec ```ruby class Minitest::Spec include FactoryBot::Syntax::Methods end ``` #### minitest-rails ```ruby class ActiveSupport::TestCase include FactoryBot::Syntax::Methods end ``` If you do not include `FactoryBot::Syntax::Methods` in your test suite, then all factory\_bot methods will need to be prefaced with `FactoryBot`. Defining factories ------------------ ### Factory name and attributes Each factory has a name and a set of attributes. The name is used to guess the class of the object by default: ```ruby # This will guess the User class FactoryBot.define do factory :user do first_name { "John" } last_name { "Doe" } admin { false } end end ``` ### Specifying the class explicitly It is also possible to explicitly specify the class: ```ruby # This will use the User class (otherwise Admin would have been guessed) factory :admin, class: "User" ``` You can pass a constant as well, if the constant is available (note that this can cause test performance problems in large Rails applications, since referring to the constant will cause it to be eagerly loaded). ```ruby factory :access_token, class: User ``` ### Hash attributes Because of the block syntax in Ruby, defining attributes as `Hash`es (for serialized/JSON columns, for example) requires two sets of curly brackets: ```ruby factory :program do configuration { { auto_resolve: false, auto_define: true } } end ``` ### Best practices It is recommended that you have one factory for each class that provides the simplest set of attributes necessary to create an instance of that class. If you're creating ActiveRecord objects, that means that you should only provide attributes that are required through validations and that do not have defaults. Other factories can be created through inheritance to cover common scenarios for each class. Attempting to define multiple factories with the same name will raise an error. ### Definition file paths Factories can be defined anywhere, but will be automatically loaded after calling `FactoryBot.find_definitions` if factories are defined in files at the following locations: test/factories.rb spec/factories.rb test/factories/*.rb spec/factories/*.rb ### Static Attributes Static attributes (without a block) are no longer available in factory\_bot 5. You can read more about the decision to remove them in [this blog post](https://robots.thoughtbot.com/deprecating-static-attributes-in-factory_bot-4-11). Using factories --------------- ### Build strategies factory\_bot supports several different build strategies: build, create, attributes\_for and build\_stubbed: ```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) # 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 ``` ### Attribute overrides No matter which strategy is used, it's possible to override the defined attributes by passing a hash: ```ruby # Build a User instance and override the first_name property user = build(:user, first_name: "Joe") user.first_name # => "Joe" ``` ### `build_stubbed` and `Marshal.dump` Note that objects created with `build_stubbed` cannot be serialized with `Marshal.dump`, since factory\_bot defines singleton methods on these objects. Aliases ------- factory\_bot allows you to define aliases to existing factories to make them easier to re-use. This could come in handy when, for example, your Post object has an author attribute that actually refers to an instance of a User class. While normally factory\_bot can infer the factory name from the association name, in this case it will look for an author factory in vain. So, alias your user factory so it can be used under alias names. ```ruby factory :user, aliases: [:author, :commenter] do first_name { "John" } last_name { "Doe" } date_of_birth { 18.years.ago } end factory :post do # The alias allows us to write author instead of # association :author, factory: :user author title { "How to read a book effectively" } body { "There are five steps involved." } end factory :comment do # The alias allows us to write commenter instead of # association :commenter, factory: :user commenter body { "Great article!" } end ``` Dependent Attributes -------------------- Attributes can be based on the values of other attributes using the evaluator that is yielded to dynamic attribute blocks: ```ruby factory :user do first_name { "Joe" } last_name { "Blow" } email { "#{first_name}.#{last_name}@example.com".downcase } end create(:user, last_name: "Doe").email # => "joe.doe@example.com" ``` Transient Attributes -------------------- Transient attributes are attributes only available within the factory definition, and not set on the object being built. This allows for more complex logic inside factories. ### With other attributes There may be times where your code can be DRYed up by passing in transient attributes to factories. You can access transient attributes within other attributes (see [Dependent Attributes](#dependent-attributes)): ```ruby factory :user do transient do rockstar { true } end name { "John Doe#{" - Rockstar" if rockstar}" } end create(:user).name #=> "John Doe - ROCKSTAR" create(:user, rockstar: false).name #=> "John Doe" ``` ### With `attributes_for` Transient attributes will be ignored within attributes\_for and won't be set on the model, even if the attribute exists or you attempt to override it. ### With callbacks If you need to access the evaluator in a factory\_bot callback, you'll need to declare a second block argument (for the evaluator) and access transient attributes from there. ```ruby factory :user do transient do upcased { false } end name { "John Doe" } after(:create) do |user, evaluator| user.name.upcase! if evaluator.upcased end end create(:user).name #=> "John Doe" create(:user, upcased: true).name #=> "JOHN DOE" ``` ### With associations Transient [associations](#associations) are not supported in factory\_bot. Associations within the transient block will be treated as regular, non-transient associations. If needed, you can generally work around this by building a factory within a transient attribute: ```ruby factory :post factory :user do transient do post { build(:post) } end end ``` Method Name / Reserved Word Attributes ------------------------------- If your attributes conflict with existing methods or reserved words (all methods in the [DefinitionProxy](https://github.com/thoughtbot/factory_bot/blob/master/lib/factory_bot/definition_proxy.rb) class) you can define them with `add_attribute`. ```ruby factory :dna do add_attribute(:sequence) { 'GATTACA' } end factory :payment do add_attribute(:method) { 'paypal' } end ``` Inheritance ----------- ### Nested factories You can easily create multiple factories for the same class without repeating common attributes by nesting factories: ```ruby factory :post do title { "A title" } factory :approved_post do approved { true } end end approved_post = create(:approved_post) approved_post.title # => "A title" approved_post.approved # => true ``` ### Assigning parent explicitly You can also assign the parent explicitly: ```ruby factory :post do title { "A title" } end factory :approved_post, parent: :post do approved { true } end ``` ### Best practices As mentioned above, it's good practice to define a basic factory for each class with only the attributes required to create it. Then, create more specific factories that inherit from this basic parent. Factory definitions are still code, so keep them DRY. Associations ------------ ### Implicit definition It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out. ```ruby factory :post do # ... author end ``` ### Explicit definition You can define associations explicitly. This can be handy especially when [Overriding attributes](#overriding-attributes) ```ruby factory :post do # ... association :author end ``` ### Inline definition You can also define associations inline within regular attributes, but note that the value will be `nil` when using the `attributes_for` strategy. ```ruby factory :post do # ... author { association :author } end ``` ### Specifying the factory You can specify a different factory (although [Aliases](#aliases) might also help you out here). Implicitly: ```ruby factory :post do # ... author factory: :user end ``` Explicitly: ```ruby factory :post do # ... association :author, factory: :user end ``` Inline: ```ruby factory :post do # ... author { association :user } end ``` ### Overriding attributes You can also override attributes. Implicitly: ```ruby factory :post do # ... author factory: :author, last_name: "Writely" end ``` Explicitly: ```ruby factory :post do # ... association :author, last_name: "Writely" end ``` Or inline using attributes from the factory: ```rb factory :post do # ... author_last_name { "Writely" } author { association :author, last_name: author_last_name } end ``` ### Association overrides Attribute overrides can be used to link associated objects: ```ruby FactoryBot.define do factory :author do author_last_name { 'Taylor' } end factory :post do author end end eunji = build(:author, name: 'Eunji') post = build(:post, author: eunji) ``` ### Build strategies In factory\_bot 5, associations default to using the same build strategy as their parent object: ```ruby FactoryBot.define do factory :author factory :post do author end end post = build(:post) post.new_record? # => true post.author.new_record? # => true post = create(:post) post.new_record? # => false post.author.new_record? # => false ``` This is different than the default behavior for previous versions of factory\_bot, where the association strategy would not always match the strategy of the parent object. If you want to continue using the old behavior, you can set the `use_parent_strategy` configuration option to `false`. ```ruby FactoryBot.use_parent_strategy = false # Builds and saves a User and a Post post = create(:post) post.new_record? # => false post.author.new_record? # => false # Builds and saves a User, and then builds but does not save a Post post = build(:post) post.new_record? # => true post.author.new_record? # => false ``` To not save the associated object, specify `strategy: :build` in the factory: ```ruby FactoryBot.use_parent_strategy = false factory :post do # ... association :author, factory: :user, strategy: :build end # Builds a User, and then builds a Post, but does not save either post = build(:post) post.new_record? # => true post.author.new_record? # => true ``` Please note that the `strategy: :build` option must be passed to an explicit call to `association`, and cannot be used with implicit associations: ```ruby factory :post do # ... author strategy: :build # <<< this does *not* work; causes author_id to be nil ``` ### `has_many` associations There are a few ways to generate data for a `has_many` relationship. The simplest approach is to write a helper method in plain Ruby to tie together the different records: ```ruby FactoryBot.define do factory :post do title { "Through the Looking Glass" } user end factory :user do name { "Rachel Sanchez" } end end def user_with_posts(posts_count: 5) FactoryBot.create(:user) do |user| FactoryBot.create_list(:post, posts_count, user: user) end end create(:user).posts.length # 0 user_with_posts.posts.length # 5 user_with_posts(posts_count: 15).posts.length # 15 ``` If you prefer to keep the object creation fully within factory\_bot, you can build the posts in an `after(:create)` callback. ```ruby FactoryBot.define do factory :post do title { "Through the Looking Glass" } user end factory :user do name { "John Doe" } # user_with_posts will create post data after the user has been created factory :user_with_posts do # posts_count is declared as a transient attribute available in the # callback via the evaluator transient do posts_count { 5 } end # the after(:create) yields two values; the user instance itself and the # evaluator, which stores all values from the factory, including transient # attributes; `create_list`'s second argument is the number of records # to create and we make sure the user is associated properly to the post after(:create) do |user, evaluator| create_list(:post, evaluator.posts_count, user: user) # You may need to reload the record here, depending on your application user.reload end end end end create(:user).posts.length # 0 create(:user_with_posts).posts.length # 5 create(:user_with_posts, posts_count: 15).posts.length # 15 ``` Or, for a solution that works with `build`, `build_stubbed`, and `create` (although it doesn't work well with `attributes_for`), you can use inline associations: ```ruby FactoryBot.define do factory :post do title { "Through the Looking Glass" } user end factory :user do name { "Taylor Kim" } factory :user_with_posts do posts { [association(:post)] } end end end create(:user).posts.length # 0 create(:user_with_posts).posts.length # 1 build(:user_with_posts).posts.length # 1 build_stubbed(:user_with_posts).posts.length # 1 ``` For more flexibility you can combine this with the `posts_count` transient attribute from the callback example: ```ruby FactoryBot.define do factory :post do title { "Through the Looking Glass" } user end factory :user do name { "Adiza Kumato" } factory :user_with_posts do transient do posts_count { 5 } end posts do Array.new(posts_count) { association(:post) } end end end end create(:user_with_posts).posts.length # 5 create(:user_with_posts, posts_count: 15).posts.length # 15 build(:user_with_posts, posts_count: 15).posts.length # 15 build_stubbed(:user_with_posts, posts_count: 15).posts.length # 15 ``` ### `has_and_belongs_to_many` associations Generating data for a `has_and_belongs_to_many` relationship is very similar to the above `has_many` relationship, with a small change: you need to pass an array of objects to the model's pluralized attribute name rather than a single object to the singular version of the attribute name. ```ruby def profile_with_languages(languages_count: 2) FactoryBot.create(:profile) do |profile| FactoryBot.create_list(:language, languages_count, profiles: [profile]) end end ``` Or with the callback approach: ```ruby factory :profile_with_languages do transient do languages_count { 2 } end after(:create) do |profile, evaluator| create_list(:language, evaluator.languages_count, profiles: [profile]) profile.reload end end ``` Or the inline association approach (note the use of the `instance` method here to refer to the profile being built): ```ruby factory :profile_with_languages do transient do languages_count { 2 } end languages do Array.new(languages_count) do association(:language, profiles: [instance]) end end end ``` ### Polymorphic associations Polymorphic associations can be handled with traits: ```ruby FactoryBot.define do factory :video factory :photo factory :comment do for_photo # default to the :for_photo trait if none is specified trait :for_video do association :commentable, factory: :video end trait :for_photo do association :commentable, factory: :photo end end end ``` This allows us to do: ```ruby create(:comment) create(:comment, :for_video) create(:comment, :for_photo) ``` ### Interconnected associations There are limitless ways objects might be interconnected, and factory\_bot may not always be suited to handle those relationships. In some cases it makes sense to use factory\_bot to build each individual object, and then to write helper methods in plain Ruby to tie those objects together. That said, some more complex, interconnected relationships can be built in factory\_bot using inline associations with reference to the `instance` being built. Let's say your models look like this, where an associated `Student` and `Profile` should both belong to the same `School`: ```ruby class Student < ApplicationRecord belongs_to :school has_one :profile end class Profile < ApplicationRecord belongs_to :school belongs_to :student end class School < ApplicationRecord has_many :students has_many :profiles end ``` We can ensure the student and profile are connected to each other and to the same school with a factory like this: ```ruby 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 ``` Note that this approach works with `build`, `build_stubbed`, and `create`, but the associations will return `nil` when using `attributes_for`. Also, note that if you assign any attributes inside a custom `initialize_with` (e.g. `initialize_with { new(**attributes) }`), those attributes should not refer to `instance`, since it will be `nil`. Sequences --------- ### Global sequences Unique values in a specific format (for example, e-mail addresses) can be generated using sequences. Sequences are defined by calling `sequence` in a definition block, and values in a sequence are generated by calling `generate`: ```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" ``` ### With dynamic attributes Sequences can be used in dynamic attributes: ```ruby factory :invite do invitee { generate(:email) } end ``` ### As implicit attributes Or as implicit attributes: ```ruby factory :user do email # Same as `email { generate(:email) }` end ``` Note that defining sequences as implicit attributes will not work if you have a factory with the same name as the sequence. ### Inline sequences And it's also possible to define an in-line sequence that is only used in a particular factory: ```ruby factory :user do sequence(:email) { |n| "person#{n}@example.com" } end ``` ### Initial value You can override the initial value. Any value that responds to the `#next` method will work (e.g. 1, 2, 3, 'a', 'b', 'c') ```ruby factory :user do sequence(:email, 1000) { |n| "person#{n}@example.com" } end ``` ### Without a block Without a block, the value will increment itself, starting at its initial value: ```ruby factory :post do sequence(:position) end ``` ### Aliases Sequences can also have aliases. The sequence aliases share the same counter: ```ruby factory :user do sequence(:email, 1000, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" } end # will increase value counter for :email which is shared by :sender and :receiver generate(:sender) ``` Define aliases and use default value (1) for the counter ```ruby factory :user do sequence(:email, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" } end ``` Setting the value: ```ruby factory :user do sequence(:email, 'a', aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" } end ``` The value just needs to support the `#next` method. Here the next value will be 'a', then 'b', etc. ### Rewinding Sequences can also be rewound with `FactoryBot.rewind_sequences`: ```ruby sequence(:email) {|n| "person#{n}@example.com" } generate(:email) # "person1@example.com" generate(:email) # "person2@example.com" generate(:email) # "person3@example.com" FactoryBot.rewind_sequences generate(:email) # "person1@example.com" ``` This rewinds all registered sequences. ### Uniqueness When working with uniqueness constraints, be careful not to pass in override values that will conflict with the generated sequence values. In this example the email will be the same for both users. If email must be unique, this code will error: ```rb factory :user do sequence(:email) { |n| "person#{n}@example.com" } end FactoryBot.create(:user, email: "person1@example.com") FactoryBot.create(:user) ``` Traits ------ ### Defining traits Traits allow you to group attributes together and then apply them to any factory. ```ruby factory :user, aliases: [:author] factory :story do title { "My awesome story" } author trait :published do published { true } end trait :unpublished do published { false } end trait :week_long_publishing do start_at { 1.week.ago } end_at { Time.now } end trait :month_long_publishing do start_at { 1.month.ago } end_at { Time.now } end factory :week_long_published_story, traits: [:published, :week_long_publishing] factory :month_long_published_story, traits: [:published, :month_long_publishing] factory :week_long_unpublished_story, traits: [:unpublished, :week_long_publishing] factory :month_long_unpublished_story, traits: [:unpublished, :month_long_publishing] end ``` ### As implicit attributes Traits can be used as implicit attributes: ```ruby factory :week_long_published_story_with_title, parent: :story do published week_long_publishing title { "Publishing that was started at #{start_at}" } end ``` Note that defining traits as implicit attributes will not work if you have a factory or sequence with the same name as the trait. ### Attribute precedence Traits that define the same attributes won't raise AttributeDefinitionErrors; the trait that defines the attribute latest gets precedence. ```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 ``` ### In child factories You can override individual attributes granted by a trait in a child factory: ```ruby factory :user do name { "Friendly User" } login { name } trait :active do name { "John Doe" } status { :active } login { "#{name} (M)" } end factory :brandon do active name { "Brandon" } end end ``` ### Using traits Traits can also be passed in as a list of symbols when you construct an instance from factory\_bot. ```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") ``` This ability works with `build`, `build_stubbed`, `attributes_for`, and `create`. `create_list` and `build_list` methods are supported as well. Just remember to pass the number of instances to create/build as second parameter, as documented in the "Building or Creating Multiple Records" section of this file. ```ruby factory :user do name { "Friendly User" } trait :admin do admin { true } end end # creates 3 admin users with :active status and name "Jon Snow" create_list(:user, 3, :admin, :active, name: "Jon Snow") ``` ### With associations Traits can be used with associations easily too: ```ruby factory :user do name { "Friendly User" } trait :admin do admin { true } end end factory :post do association :user, :admin, name: 'John Doe' end # creates an admin user with name "John Doe" create(:post).user ``` When you're using association names that're different than the factory: ```ruby factory :user do name { "Friendly User" } trait :admin do admin { true } end end factory :post do association :author, :admin, factory: :user, name: 'John Doe' # or association :author, factory: [:user, :admin], name: 'John Doe' end # creates an admin user with name "John Doe" create(:post).author ``` ### Traits within traits Traits can be used within other traits to mix in their attributes. ```ruby factory :order do trait :completed do completed_at { 3.days.ago } end trait :refunded do completed refunded_at { 1.day.ago } end end ``` ### With transient attributes Finally, traits can accept transient attributes. ```ruby factory :invoice do trait :with_amount do transient do amount { 1 } end after(:create) do |invoice, evaluator| create :line_item, invoice: invoice, amount: evaluator.amount end end end create :invoice, :with_amount, amount: 2 ``` ### Enum traits Given an Active Record model with an enum attribute: ```rb class Task < ActiveRecord::Base enum status: {queued: 0, started: 1, finished: 2} end ``` factory\_bot will automatically define traits for each possible value of the enum: ```rb FactoryBot.define do factory :task end FactoryBot.build(:task, :queued) FactoryBot.build(:task, :started) FactoryBot.build(:task, :finished) ``` Writing the traits out manually would be cumbersome, and is not necessary: ```rb FactoryBot.define do factory :task do trait :queued do status { :queued } end trait :started do status { :started } end trait :finished do status { :finished } end end end ``` If automatically defining traits for enum attributes on every factory is not desired, it is possible to disable the feature by setting `FactoryBot.automatically_define_enum_traits = false` In that case, it is still possible to explicitly define traits for an enum attribute in a particular factory: ```rb FactoryBot.automatically_define_enum_traits = false FactoryBot.define do factory :task do traits_for_enum(:status) end end ``` It is also possible to use this feature for other enumerable values, not specifically tied to Active Record enum attributes. With an array: ```rb class Task attr_accessor :status end FactoryBot.define do factory :task do traits_for_enum(:status, ["queued", "started", "finished"]) end end ``` Or with a hash: ```rb class Task attr_accessor :status end FactoryBot.define do factory :task do traits_for_enum(:status, { queued: 0, started: 1, finished: 2 }) end end ``` Callbacks --------- ### Default callbacks factory\_bot makes available four callbacks for injecting some code: * after(:build) - called after a factory is built (via `FactoryBot.build`, `FactoryBot.create`) * before(:create) - called before a factory is saved (via `FactoryBot.create`) * after(:create) - called after a factory is saved (via `FactoryBot.create`) * after(:stub) - called after a factory is stubbed (via `FactoryBot.build_stubbed`) Examples: ```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 ``` Note that you'll have an instance of the user in the block. This can be useful. ### Multiple callbacks You can also define multiple types of callbacks on the same factory: ```ruby factory :user do after(:build) { |user| do_something_to(user) } after(:create) { |user| do_something_else_to(user) } end ``` Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified: ```ruby factory :user do after(:create) { this_runs_first } after(:create) { then_this } end ``` Calling `create` will invoke both `after_build` and `after_create` callbacks. Also, like standard attributes, child factories will inherit (and can also define) callbacks from their parent factory. Multiple callbacks can be assigned to run a block; this is useful when building various strategies that run the same code (since there are no callbacks that are shared across all strategies). ```ruby factory :user do callback(:after_stub, :before_create) { do_something } after(:stub, :create) { do_something_else } before(:create, :custom) { do_a_third_thing } end ``` ### Global callbacks To override callbacks for all factories, define them within the `FactoryBot.define` block: ```ruby FactoryBot.define do after(:build) { |object| puts "Built #{object}" } after(:create) { |object| AuditLog.create(attrs: object.attributes) } factory :user do name { "John Doe" } end end ``` ### Symbol#to_proc You can call callbacks that rely on `Symbol#to_proc`: ```ruby # app/models/user.rb class User < ActiveRecord::Base def confirm! # confirm the user account end end # spec/factories.rb FactoryBot.define do factory :user do after :create, &:confirm! end end create(:user) # creates the user and confirms it ``` Modifying factories ------------------- If you're given a set of factories (say, from a gem developer) but want to change them to fit into your application better, you can modify that factory instead of creating a child factory and adding attributes there. If a gem were to give you a User factory: ```ruby FactoryBot.define do factory :user do full_name { "John Doe" } sequence(:username) { |n| "user#{n}" } password { "password" } end end ``` Instead of creating a child factory that added 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 ``` You could modify that factory instead. ```ruby FactoryBot.modify do factory :user do full_name { "Jane Doe" } date_of_birth { 21.years.ago } health { 90 } end end ``` When modifying a factory, you can change any of the attributes you want (aside from callbacks). `FactoryBot.modify` must be called outside of a `FactoryBot.define` block as it operates on factories differently. A caveat: you can only modify factories (not sequences or traits) and callbacks *still compound as they normally would*. So, if the factory you're modifying defines an `after(:create)` callback, you defining an `after(:create)` won't override it, it'll just get run after the first callback. Building or Creating Multiple Records ------------------------------------- Sometimes, you'll want to create or build multiple instances of a factory at once. ```ruby built_users = build_list(:user, 25) created_users = create_list(:user, 25) ``` These methods will build or create a specific amount of factories and return them as an array. To set the attributes for each of the factories, you can pass in a hash as you normally would. ```ruby twenty_year_olds = build_list(:user, 25, date_of_birth: 20.years.ago) ``` In order to set different attributes for each factory, these methods may be passed a block, with the factory and the index as parameters: ```ruby twenty_somethings = build_list(:user, 10) do |user, i| user.date_of_birth = (20 + i).years.ago end ``` `build_stubbed_list` will give you fully stubbed out instances: ```ruby stubbed_users = build_stubbed_list(:user, 25) # array of stubbed users ``` There's also a set of `*_pair` methods for creating two records at a time: ```ruby built_users = build_pair(:user) # array of two built users created_users = create_pair(:user) # array of two created users ``` If you need multiple attribute hashes, `attributes_for_list` will generate them: ```ruby users_attrs = attributes_for_list(:user, 25) # array of attribute hashes ``` Linting Factories ----------------- factory\_bot allows for linting known factories: ```ruby FactoryBot.lint ``` `FactoryBot.lint` creates each factory and catches any exceptions raised during the creation process. `FactoryBot::InvalidFactoryError` is raised with a list of factories (and corresponding exceptions) for factories which could not be created. Recommended usage of `FactoryBot.lint` is to run this in a task before your test suite is executed. Running it in a `before(:suite)`, will negatively impact the performance of your tests when running single tests. Example Rake task: ```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 ``` After calling `FactoryBot.lint`, you'll likely want to clear out the database, as records will most likely be created. The provided example above uses an sql transaction and rollback to leave the database clean. You can lint factories selectively by passing only factories you want linted: ```ruby factories_to_lint = FactoryBot.factories.reject do |factory| factory.name =~ /^old_/ end FactoryBot.lint factories_to_lint ``` This would lint all factories that aren't prefixed with `old_`. Traits can also be linted. This option verifies that each and every trait of a factory generates a valid object on its own. This is turned on by passing `traits: true` to the `lint` method: ```ruby FactoryBot.lint traits: true ``` This can also be combined with other arguments: ```ruby FactoryBot.lint factories_to_lint, traits: true ``` You can also specify the strategy used for linting: ```ruby FactoryBot.lint strategy: :build ``` Verbose linting will include full backtraces for each error, which can be helpful for debugging: ```ruby FactoryBot.lint verbose: true ``` Custom Construction ------------------- If you want to use factory\_bot to construct an object where some attributes are passed to `initialize` or if you want to do something other than simply calling `new` on your build class, you can override the default behavior by defining `initialize_with` on your factory. Example: ```ruby # user.rb class User attr_accessor :name, :email def initialize(name) @name = name end end # factories.rb sequence(:email) { |n| "person#{n}@example.com" } factory :user do name { "Jane Doe" } email initialize_with { new(name) } end build(:user).name # Jane Doe ``` Although factory\_bot is written to work with ActiveRecord out of the box, it can also work with any Ruby class. For maximum compatibility with ActiveRecord, the default initializer builds all instances by calling `new` on your build class without any arguments. It then calls attribute writer methods to assign all the attribute values. While that works fine for ActiveRecord, it actually doesn't work for almost any other Ruby class. You can override the initializer in order to: * Build non-ActiveRecord objects that require arguments to `initialize` * Use a method other than `new` to instantiate the instance * Do wild things like decorate the instance after it's built When using `initialize_with`, you don't have to declare the class itself when calling `new`; however, any other class methods you want to call will have to be called on the class explicitly. For example: ```ruby factory :user do name { "John Doe" } initialize_with { User.build_with_name(name) } end ``` You can also access all public attributes within the `initialize_with` block by calling `attributes`: ```ruby factory :user do transient do comments_count { 5 } end name "John Doe" initialize_with { new(**attributes) } end ``` This will build a hash of all attributes to be passed to `new`. It won't include transient attributes, but everything else defined in the factory will be passed (associations, evaluated sequences, etc.) You can define `initialize_with` for all factories by including it in the `FactoryBot.define` block: ```ruby FactoryBot.define do initialize_with { new("Awesome first argument") } end ``` When using `initialize_with`, attributes accessed from within the `initialize_with` block are assigned *only* in the constructor; this equates to roughly the following code: ```ruby FactoryBot.define do factory :user do initialize_with { new(name) } name { 'value' } end end build(:user) # runs User.new('value') ``` This prevents duplicate assignment; in versions of factory\_bot before 4.0, it would run this: ```ruby FactoryBot.define do factory :user do initialize_with { new(name) } name { 'value' } end end build(:user) # runs user = User.new('value') user.name = 'value' ``` Custom Strategies ----------------- There are times where you may want to extend behavior of factory\_bot by adding a custom build strategy. Strategies define two methods: `association` and `result`. `association` receives a `FactoryBot::FactoryRunner` instance, upon which you can call `run`, overriding the strategy if you want. The second method, `result`, receives a `FactoryBot::Evaluation` instance. It provides a way to trigger callbacks (with `notify`), `object` or `hash` (to get the result instance or a hash based on the attributes defined in the factory), and `create`, which executes the `to_create` callback defined on the factory. To understand how factory\_bot uses strategies internally, it's probably easiest to just view the source for each of the four default strategies. Here's an example of composing a strategy using `FactoryBot::Strategy::Create` to build a JSON representation of your model. ```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 end ``` For factory\_bot to recognize the new strategy, you can register it: ```ruby FactoryBot.register_strategy(:json, JsonStrategy) ``` This allows you to call ```ruby FactoryBot.json(:user) ``` Finally, you can override factory\_bot's own strategies if you'd like by registering a new object in place of the strategies. Custom Callbacks ---------------- Custom callbacks can be defined if you're using custom strategies: ```ruby class JsonStrategy def initialize @strategy = FactoryBot.strategy_by_name(:create).new end delegate :association, to: :@strategy def result(evaluation) result = @strategy.result(evaluation) evaluation.notify(:before_json, result) result.to_json.tap do |json| evaluation.notify(:after_json, json) evaluation.notify(:make_json_awesome, json) end end end FactoryBot.register_strategy(:json, JsonStrategy) FactoryBot.define do factory :user do before(:json) { |user| do_something_to(user) } after(:json) { |user_json| do_something_to(user_json) } callback(:make_json_awesome) { |user_json| do_something_to(user_json) } end end ``` Custom Methods to Persist Objects --------------------------------- By default, creating a record will call `save!` on the instance; since this may not always be ideal, you can override that behavior by defining `to_create` on the factory: ```ruby factory :different_orm_model do to_create { |instance| instance.persist! } end ``` To disable the persistence method altogether on create, you can `skip_create` for that factory: ```ruby factory :user_without_database do skip_create end ``` To override `to_create` for all factories, define it within the `FactoryBot.define` block: ```ruby FactoryBot.define do to_create { |instance| instance.persist! } factory :user do name { "John Doe" } end end ``` ActiveSupport Instrumentation ----------------------------- In order to track what factories are created (and with what build strategy), `ActiveSupport::Notifications` are included to provide a way to subscribe to factories being run. One example would be to track factories based on a threshold of execution time. ```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 ``` Another example would be tracking all factories and how they're used throughout your test suite. If you're using RSpec, it's as simple as adding a `before(:suite)` and `after(:suite)`: ```ruby factory_bot_results = {} config.before(:suite) do ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload| factory_name = payload[:name] strategy_name = payload[:strategy] factory_bot_results[factory_name] ||= {} factory_bot_results[factory_name][strategy_name] ||= 0 factory_bot_results[factory_name][strategy_name] += 1 end end config.after(:suite) do puts factory_bot_results end ``` Rails Preloaders and RSpec -------------------------- When running RSpec with a Rails preloader such as `spring` or `zeus`, it's possible to encounter an `ActiveRecord::AssociationTypeMismatch` error when creating a factory with associations, as below: ```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 ``` The error occurs during the run of the test suite: ``` Failure/Error: united_states = create(:united_states) ActiveRecord::AssociationTypeMismatch: LocationGroup(#70251250797320) expected, got LocationGroup(#70251200725840) ``` The two possible solutions are to either run the suite without the preloader, or to add `FactoryBot.reload` to the RSpec configuration, like so: ```ruby RSpec.configure do |config| config.before(:suite) { FactoryBot.reload } end ``` Using Without Bundler --------------------- If you're not using Bundler, be sure to have the gem installed and call: ```ruby require 'factory_bot' ``` Once required, assuming you have a directory structure of `spec/factories` or `test/factories`, all you'll need to do is run: ```ruby FactoryBot.find_definitions ``` If you're using a separate directory structure for your factories, you can change the definition file paths before trying to find definitions: ```ruby FactoryBot.definition_file_paths = %w(custom_factories_directory) FactoryBot.find_definitions ``` If you don't have a separate directory of factories and would like to define them inline, that's possible as well: ```ruby require 'factory_bot' FactoryBot.define do factory :user do name { 'John Doe' } date_of_birth { 21.years.ago } end end ``` factory_bot-6.2.0/Gemfile000066400000000000000000000002321404526231600153250ustar00rootroot00000000000000source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gemspec name: "factory_bot" factory_bot-6.2.0/Gemfile.lock000066400000000000000000000077251404526231600162720ustar00rootroot00000000000000PATH remote: . specs: factory_bot (6.2.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (6.1.3) activesupport (= 6.1.3) activerecord (6.1.3) activemodel (= 6.1.3) activesupport (= 6.1.3) activesupport (6.1.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) zeitwerk (~> 2.3) appraisal (2.3.0) bundler rake thor (>= 0.14.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (2.0.4) concurrent-ruby (~> 1.0) unicode-display_width (2.0.0) yard (0.9.26) zeitwerk (2.4.2) PLATFORMS ruby DEPENDENCIES activerecord activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.2.16 factory_bot-6.2.0/LICENSE000066400000000000000000000020701404526231600150410ustar00rootroot00000000000000Copyright (c) 2008-2019 Joe Ferris and thoughtbot, inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. factory_bot-6.2.0/NAME.md000066400000000000000000000014111404526231600150740ustar00rootroot00000000000000# Project Naming History ## Factory Girl This library was [initially released](https://robots.thoughtbot.com/waiting-for-a-factory-girl) in 2008 with the name "Factory Girl". We chose the name as a nod in the direction of the [Factory method](https://en.wikipedia.org/wiki/Factory_method_pattern) and [Object Mother](http://martinfowler.com/bliki/ObjectMother.html) software patterns from the _Design Patterns_ book, and as a reference to the [Rolling Stones song](https://www.youtube.com/watch?v=4jKix2DFlnA) of the same name. ## Factory Bot The name "Factory Girl" was confusing to some developers who encountered this library, and offensive or problematic to others. In October 2017 we [renamed the library](https://robots.thoughtbot.com/factory_bot) to "Factory Bot". factory_bot-6.2.0/NEWS.md000066400000000000000000000421741404526231600151430ustar00rootroot00000000000000# News ## 6.2.0 (May 7, 2021) * Added: support for Ruby 3.0 * Changed: Include factory or trait name in error messages for missing traits. d05a9a3c * Changed: Switched from Travis CI to GitHub Actions * Fixed: More Ruby 2.7 kwarg deprecation warnings ## 6.1.0 (July 8, 2020) * Added: public reader for the evaluation instance, helpful for building interrelated associations * Changed: raise a more helpful error when passing an invalid argument to an association * Fixed: Ruby 2.7 kwarg deprecation warnings ## 6.0.2 (June 19, 2020) * Fixed: bug causing traits to consume more memory each time they were used ## 6.0.1 (June 19, 2020) * Fixed: bug with constant resolution causing unexpected uninitialized constant errors ## 6.0.0 (June 18, 2020) * Added: automatic definition of traits for Active Record enum attributes, enabled by default (Note that this required changing where factory_bot constantizes the build class, which may affect applications that were using abstract factories for inheritance. See issue #1409.) * Added: `traits_for_enum` method to define traits for non-Active Record enums * Added: `build_stubbed_starting_id=` option to define the starting id for `build_stubbed` * Removed: deprecated methods on the top-level `FactoryBot` module meant only for internal use * Removed: support for EOL versions of Ruby (2.3, 2.4) and Rails (4.2) * Removed: support for "abstract" factories with no associated class; use traits instead. ## 5.2.0 (April 24, 2020) * Added: Pass index to block for `*_list` methods * Deprecated: methods on the top-level `FactoryBot` module meant only for internal use: `callbacks`, `configuration`, `constructor`, `initialize_with`, `register_sequence`, `resent_configuration`, `skip_create`, `to_create` ## 5.1.2 (March 25, 2020) * Fixed: Ruby 2.7 keyword deprecation warning in FactoryBot.lint ## 5.1.1 (October 2, 2019) * Improved: performance of traits * Fixed: registering strategies on JRuby ## 5.1.0 (September 21, 2019) * Added: "Did you mean?" style error message to help with typos in association declarations * Changed: `NoMethodError` for static attributes now offers a "Did you mean?" style message * Fixed: avoid undefining inherited evaluator methods * Fixed: avoid stubbing id for records without a primary key * Fixed: raise a helpful error for self-referencing traits to avoid a `SystemStackError` * Deprecated: methods on the top-level `FactoryBot` module meant only for internal use: `allow_class_lookup`, `allow_class_lookup`=, `register_trait`, `trait_by_name`, `traits`, `sequence_by_name`, `sequences`, `factory_by_name`, `register_factory`, `callback_names`, `register_callback`, `register_default_callbacks`, `register_default_strategies`, `strategies` ## 5.0.2 (February 22, 2019) * Bugfix: raise "Trait not registered" error when passing invalid trait arguments ## 5.0.1 (February 15, 2019) * Bugfix: Do not raise error when two sequences have the same name in two traits that have the same name ## 5.0.0 (February 1, 2019) * Added: Verbose option to include full backtraces in the linting output * Changed: use_parent_strategy now defaults to true, so by default the build strategy will build, rather than create associations * Changed: Passing a block when defining associations now raises an error * Bugfix: use_parent_strategy is no longer reset by FactoryBot.reload * Bugfix: rewind_sequences will now rewind local sequences along with the global ones * Bugfix: the build_stubbed strategy now sets timestamps without changing the the original behavior of the timestamp methods * Bugfix: avoid a stack error when referring to an "attributes" attribute in initialize_with * Removed: support for EOL versions of Ruby and Rails * Removed: static attributes (use dynamic attributes with a block instead) * Removed: looking up factories by class * Removed: ignore method (use transient instead) * Removed: duplicate_attribute_assignment_from_initialize_with configuration option * Deprecated: allow_class_lookup configuration option ## 4.11.1 (September 7, 2018) * Documentation: Include .yardopts in the gem to fix broken RubyDoc links ## 4.11.0 (August, 15, 2018) * Bugfix: Do not raise error for valid build_stubbed methods: decrement, increment, and toggle * Bugfix: Do not add timestamps with build_stubbed for objects that shouldn't have timestamps * Deprecate static attributes ## 4.10.0 (May 25, 2018) * Allow sequences to be rewound ## 4.9.0 (skipped - FactoryGirl only release) ## 4.8.2 (October 20, 2017) * Rename factory_girl to factory_bot ## 4.8.1 (September 28, 2017) * Explicitly define `#destroyed?` within the `Stub` strategy to return `nil` instead of raising * Update various dependencies * Update internal test suite to use RSpec's mocking/stubbing instead of mocha ## 4.8.0 (December 16, 2016) * Improve documentation * Add `FactoryGirl.generate_list` to be consistent with `build_list`/`create_list` and friends * Add `FactoryGirl.use_parent_strategy` configuration to allow associations to leverage parent build strategy ## 4.7.0 (April 1, 2016) * Improve documentation * Improve instrumentation payload to include traits, overrides, and the factory itself * Allow linting of traits * Deprecate factory lookup by class name in preparation for 5.0 * Improve internal performance by using flat_map instead of map and compact * Improve handling of dirty attributes after building a stubbed object * Reduce warnings from redefining methods ## 4.6.0 (skipped) ## 4.5.0 (October 17, 2014) * Improve FactoryGirl.lint by including exception and message in output * Allow selective linting * Use more explicit #public_send when doing attribute assignment * Improve documentation around FactoryGirl.lint and initialize_with * Deprecate #ignore in favor of #transient ## 4.4.0 (February 10, 2014) * Add FactoryGirl.lint * Fix memory leak in duplicate traits * Update documentation ## 4.3.0 (November 3, 2013) * Start testing against Rails 4.0 and Ruby 2.0.0 * Stop testing against Rails 3.0 and Ruby 1.9.2 * Add `*_pair` methods to only build two objects * Raise if a method is defined with a FactoryGirl block (factory or trait) * Allow use of Symbol#to_proc in callbacks * Add global callbacks * Improve GETTING_STARTED and README ## 4.2.0 (January 18, 2013) * Improve documentation * Allow `*_list` syntax methods to accept a block * Update gem dependencies * Allow setting id for objects created with `build_stubbed` * Fix Stub strategy to mimic ActiveRecord regarding `created_at` * Evaluate sequences within the context of an Evaluator * Fix Mocha deprecation warning * Fix some warnings when running RUBYOPT=-w rake * Convert test suite to RSpec's "expect" syntax ## 4.1.0 (September 11, 2012) * Allow multiple callbacks to bind to the same block * Fix documentation surrounding the stub strategy ## 4.0.0 (August 3, 2012) * Remove deprecated cucumber_steps * Remove deprecated alternate syntaxes * Deprecate duplicate_attribute_assignment_from_initialize_with, which is now unused as attributes assigned within initialize_with are not subsequently assigned ## 3.6.1 (August 2, 2012) Update README to include info about running with JRuby * Update dependencies on RSpec and tiny versions of Rails in Appraisal * Improve flexibility of using traits with associations and add documentation * Stub update_column to raise to mirror ActiveRecord's change from update_attribute ## 3.6.0 (July 27, 2012) * Code/spec cleanup * Allow factories with traits to be used in associations * Refactor Factory to use DefinitionHierarchy to handle managing callbacks, custom constructor, and custom to_create * Add memoization to speed up factories providing attribute overrides * Add initial support of JRuby when running in 1.9 mode * Improve docs on what happens when including FactoryGirl::Syntax::Methods ## 3.5.0 (June 22, 2012) * Allow created_at to be set when using build_stubbed * Deprecate FactoryGirl step definitions ## 3.4.2 (June 19, 2012) * Fix bug in traits with callbacks called implicitly in factories whose callbacks trigger multiple times ## 3.4.1 (June 18, 2012) * Fix traits so they can be nested and referred to from other traits ## 3.4.0 (June 11, 2012) * Sequences support Enumerators * Optionally disable duplicate assignment of attributes in initialize_with * Make hash of public attributes available in initialize_with * Support referring to a factory based on class name ## 3.3.0 (May 13, 2012) * Allow to_create, skip_create, and initialize_with to be defined globally * Allow to_create, skip_create, and initialize_with to be defined within traits * Fix deprecation messages for alternate syntaxes (make, generate, etc.) * Improve library documentation * Deprecate after_build, after_create, before_create, after_stub in favor of new callbacks * Introduce new callback syntax: after(:build) {}, after(:custom) {}, or callback(:different) {} This allows for declaring any callback, usable with custom strategies * Add attributes_for_list and build_stubbed_list with the StrategySyntaxMethodRegistrar * Allow use of syntax methods (build, create, generate, etc) implicitly in callbacks * Internal refactoring of a handful of components ## 3.2.0 (April 24, 2012) * Use AS::Notifications for pub/sub to track running factories * Call new within initialize_with implicitly on the build class * Skip to_create with skip_create * Allow registration of custom strategies * Deprecate alternate syntaxes * Implicitly call factory_bot's syntax methods from dynamic attributes ## 3.1.0 (April 6, 2012) * Sequences support aliases, which reference the same block * Update documentation * Add before_create callback * Support use of #attribute_names method to determine available attributes for steps * Use ActiveSupport::Deprecation for all deprecations ## 3.0.0 (March 23, 2012) * Deprecate the vintage syntax * Remove Rails 2.x support * Remove Ruby 1.8 support * Remove deprecated features, including default_strategy, factory_name, :method for defining default strategy, ignore on individual attributes, and interacting with Factory the way you would FactoryGirl ## 2.6.4 (March 16, 2012) * Do not ignore names of transient attributes * Ensure attributes set on instance are calculated uniquely ## 2.6.3 (March 9, 2012) * Fix issue with traits not being present the first time a factory is accessed * Update available Cucumber step definitions to not require a trailing colon when building a table of attributes to instantiate records with ## 2.6.2 (March 9, 2012) * Allow factories to use all their ancestors' traits * Ignore bin dir generated by bundler * Namespace ::Factory as top-level to fix vintage syntax issue with Ruby 1.9.2-p3p18 ## 2.6.1 (March 2, 2012) * Use FactoryGirl.reload in specs * Clean up running named factories with a particular strategy with FactoryGirl::FactoryRunner ## 2.6.0 (February 17, 2012) * Improve documentation of has_many associations in the GETTING_STARTED document * Deprecate :method in favor of :strategy when overriding an association's build strategy ## 2.5.2 (February 10, 2012) * Fix step definitions to use associations defined in parent factories * Add inline trait support to (build|create)_list * Update ActiveSupport dependency to >= 2.3.9, which introduced class_attribute ## 2.5.1 (February 3, 2012) * Fix attribute evaluation when the attribute isn't defined in the factory but is a private method on Object * Update rubygems on Travis before running tests * Fix spec name * Update GETTING_STARTED with correct usage of build_stubbed * Update README with more info on initialize_with * Honor :parent on factory over block nesting ## 2.5.0 (January 20, 2012) * Revert 'Deprecate build_stubbed and attributes_for' * Implement initialize_with to allow overriding object instantiation * Ensure FG runs against Rails 3.2.0 ## 2.4.2 (January 18, 2012) * Fix inline traits' interaction with defaults on the factory ## 2.4.1 (January 17, 2012) * Deprecate build_stubbed and attributes_for * Fix inline traits ## 2.4.0 (January 13, 2012) * Refactor internals of FactoryGirl to use anonymous class on which attributes get defined * Explicitly require Ruby 1.8.7 or higher in gemspec * Fix documentation * Add Gemnasium status to documentation * Supplying a Class to a factory that overrides to_s no longer results in getting the wrong Class constructed * Be more agnostic about ORMs when using columns in FactoryGirl step definitions * Test against Active Record 3.2.0.rc2 * Update GETTING_STARTED to use Ruby syntax highlighting ## 2.3.2 (November 26, 2011) * Move logic of where instance.save! is set to Definition * Fix method name from aliases_for? to alias_for? * Refactor internal attribute handling to use an anonymous class instead of faking Ruby's variable resolution. This allows for more sane usage of attributes without having to manage sorting priority because attributes can turn themselves into procs, which are used with define_method on a class so attributes work correctly all the time. ## 2.3.1 (November 23, 2011) * Remove internally-used associate method from all the FactoryGirl::Proxy subclasses * Move around requiring of files * Consolidate errors into factory_bot.rb * Refactor AttributeList to deal with priority only when iterating over attributes * Refactor internals of some of the Proxy subclasses * Ensure callbacks on traits are executed in the correct order ## 2.3.0 (November 18, 2011) * Registries are named, resulting in better messages when factories, traits, or sequences cannot be found * Fix incorrect tests * Internals refactoring introducing FactoryGirl::NullFactory, FactoryGirl::Definition, and FactoryGirl::DeclarationList * Use ActiveSupport for Hash#except and its delegation capabilities * Fix usage of callbacks when added via implicit traits * Use Bundler tasks and clean up dependencies * Fix failing spec for big letters in factory name passed as symbol * Add ability for traits to be added dynamically when creating an instance via build, create, build_stubbed, or attributes_for ## 2.2.0 (October 14, 2011) * Clean up RSpec suite to not use 'should' * Use create_list in step definitions * Syntax methods that deal with ORM interaction (attributes_for, build, build_stubbed, and create) now accept a block that yields the result. This results in a more convenient way to interact with the result than using Object.tap. * Standardize deprecation warnings * Update transient attribute syntax to use blocks instead of calling ignore on each attribute declaration * Parents can be defined after children because factories are evaluated when they're used; this means breaking up factories across multiple files will behave as expected * Large internal refactoring, including changing access modifiers for a handful of methods for a more clearly defined API ## 2.1.2 (September 23, 2011) * Bugfix: Vintage syntax fixed after bug introduced in 2.1.1 * Introduce dependency on activesupport to remove code from Factory class ## 2.1.1 (September 23, 2011) (yanked) * Bugfix: Parent object callbacks are run before child object callbacks * Declarations: allow overriding/modification of individual traits in child factories * Callbacks refactored to not be attributes * Updating documentation for formatting and clarity (incl. new specificity for cucumber) ## 2.1.0 (September 02, 2011) * Bugfix: created_at now defined for stubbed models * Gemspec updated for use with Rails 3.1 * Factories can now be modified post-definition (useful for overriding defaults from gems/plugins) * All factories can now be reloaded with Factory.reload * Add :method => build to factory associations to prevent saving of associated objects * Factories defined in {Rails.root}/factories are now loaded by default * Various documentation updates ## 1.1.4 (November 28, 2008) * Factory.build now uses Factory.create for associations of the built object * Factory definitions are now detected in subdirectories, such as factories/person_factory.rb (thanks to Josh Nichols) * Factory definitions are now loaded after the environment in a Rails project (fixes some issues with dependencies being loaded too early) (thanks to Josh Nichols) * Factory names ending in 's' no longer cause problems (thanks to Alex Sharp and Josh Owens) ## 1.1.3 (September 12, 2008) * Automatically pull in definitions from factories.rb, test/factories.rb, or spec/factories.rb ## 1.1.2 (July 30, 2008) * Improved error handling for invalid and undefined factories/attributes * Improved handling of strings vs symbols vs classes * Added a prettier syntax for handling associations * Updated documentation and fixed compatibility with Rails 2.1 ## 1.1.1 (June 23, 2008) * The attribute "name" no longer requires using #add_attribute ## 1.1.0 (June 03, 2008) * Added support for dependent attributes * Fixed the attributes_for build strategy to not build associations * Added support for sequences ## 1.0.0 (May 31, 2008) * First version factory_bot-6.2.0/README.md000066400000000000000000000074601404526231600153230ustar00rootroot00000000000000# factory_bot [![Build Status][ci-image]][ci] [![Code Climate][grade-image]][grade] [![Gem Version][version-image]][version] factory_bot is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance. If you want to use factory_bot with Rails, see [factory_bot_rails](https://github.com/thoughtbot/factory_bot_rails). _[Interested in the history of the project name?][NAME]_ ### Transitioning from factory\_girl? Check out the [guide](https://github.com/thoughtbot/factory_bot/blob/4-9-0-stable/UPGRADE_FROM_FACTORY_GIRL.md). Documentation ------------- You should find the documentation for your version of factory_bot on [Rubygems](https://rubygems.org/gems/factory_bot). See [GETTING_STARTED] for information on defining and using factories. We also have [a detailed introductory video][], available for free on Upcase. [a detailed introductory video]: https://upcase.com/videos/factory-bot?utm_source=github&utm_medium=open-source&utm_campaign=factory-girl Install -------- Add the following line to Gemfile: ```ruby gem 'factory_bot' ``` and run `bundle install` from your shell. To install the gem manually from your shell, run: ```shell gem install factory_bot ``` Supported Ruby versions ----------------------- Supported Ruby versions are listed in [`.github/workflows/build.yml`](https://github.com/thoughtbot/factory_bot/blob/master/.github/workflows/build.yml) More Information ---------------- * [Rubygems](https://rubygems.org/gems/factory_bot) * [Stack Overflow](https://stackoverflow.com/questions/tagged/factory-bot) * [Issues](https://github.com/thoughtbot/factory_bot/issues) * [GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS](https://robots.thoughtbot.com/) [GETTING_STARTED]: https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md [NAME]: https://github.com/thoughtbot/factory_bot/blob/master/NAME.md Useful Tools ------------ * [FactoryTrace](https://github.com/djezzzl/factory_trace) - helps to find unused factories and traits. Contributing ------------ Please see [CONTRIBUTING.md](https://github.com/thoughtbot/factory_bot/blob/master/CONTRIBUTING.md). factory_bot was originally written by Joe Ferris and is maintained by thoughtbot. Many improvements and bugfixes were contributed by the [open source community](https://github.com/thoughtbot/factory_bot/graphs/contributors). License ------- factory_bot is Copyright © 2008-2020 Joe Ferris and thoughtbot. It is free software, and may be redistributed under the terms specified in the [LICENSE] file. [LICENSE]: https://github.com/thoughtbot/factory_bot/blob/master/LICENSE About thoughtbot ---------------- ![thoughtbot](https://thoughtbot.com/brand_assets/93:44.svg) factory_bot is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc. We love open source software! See [our other projects][community] or [hire us][hire] to design, develop, and grow your product. [community]: https://thoughtbot.com/community?utm_source=github [hire]: https://thoughtbot.com/hire-us?utm_source=github [ci-image]: https://github.com/thoughtbot/factory_bot/actions/workflows/build.yml/badge.svg [ci]: https://github.com/thoughtbot/factory_bot/actions?query=workflow%3A.github%2Fworkflows%2Fbuild.yml+branch%3Amaster++ [grade-image]: https://codeclimate.com/github/thoughtbot/factory_bot/badges/gpa.svg [grade]: https://codeclimate.com/github/thoughtbot/factory_bot [version-image]: https://badge.fury.io/rb/factory_bot.svg [version]: https://badge.fury.io/rb/factory_bot [hound-badge-image]: https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg [hound]: https://houndci.com factory_bot-6.2.0/RELEASING.md000066400000000000000000000021461404526231600156730ustar00rootroot00000000000000# Releasing 1. Update version file accordingly and run `bundle install` to update the Gemfile.lock and `bundle exec appraisal install` to update the Appraisal gemfile.lock files. 1. Update `NEWS.md` to reflect the changes since last release. 1. Commit changes. There shouldn't be code changes, and thus CI doesn't need to run, so you can add "[ci skip]" to the commit message. 1. Tag the release: `git tag -s vVERSION` - We recommend the [_quick guide on how to sign a release_] from git ready. 1. Push changes: `git push && git push --tags` 1. Build and publish: ```bash gem build factory_bot.gemspec gem push factory_bot-VERSION.gem ``` 1. Add a new GitHub release using the recent `NEWS.md` as the content. Sample URL: https://github.com/thoughtbot/factory_bot/releases/new?tag=vVERSION 1. Announce the new release, making sure to say "thank you" to the contributors who helped shape this version! thoughtbotters can refer to the handbook for announcements guidelines. [_quick guide on how to sign a release_]: http://gitready.com/advanced/2014/11/02/gpg-sign-releases.html factory_bot-6.2.0/Rakefile000066400000000000000000000015551404526231600155100ustar00rootroot00000000000000require "rubygems" require "bundler" require "rake" require "yard" require "rspec/core/rake_task" require "cucumber/rake/task" require "standard/rake" Bundler::GemHelper.install_tasks(name: "factory_bot") desc "Default: run the specs, features, and standard ." task default: %w[spec:unit spec:acceptance features standard] namespace :spec do desc "Run unit specs" RSpec::Core::RakeTask.new("unit") do |t| t.pattern = "spec/{*_spec.rb,factory_bot/**/*_spec.rb}" end desc "Run acceptance specs" RSpec::Core::RakeTask.new("acceptance") do |t| t.pattern = "spec/acceptance/**/*_spec.rb" end end desc "Run the unit and acceptance specs" task spec: ["spec:unit", "spec:acceptance"] Cucumber::Rake::Task.new(:features) do |t| t.fork = true t.cucumber_opts = ["--format", (ENV["CUCUMBER_FORMAT"] || "progress")] end YARD::Rake::YardocTask.new do |t| end factory_bot-6.2.0/cucumber.yml000066400000000000000000000000361404526231600163640ustar00rootroot00000000000000default: -r features features factory_bot-6.2.0/factory_bot.gemspec000066400000000000000000000025721404526231600177230ustar00rootroot00000000000000$LOAD_PATH << File.expand_path("lib", __dir__) require "factory_bot/version" Gem::Specification.new do |s| s.name = "factory_bot" s.version = FactoryBot::VERSION s.summary = "factory_bot provides a framework and DSL for defining and "\ "using model instance factories." s.description = "factory_bot provides a framework and DSL for defining and "\ "using factories - less error-prone, more explicit, and "\ "all-around easier to work with than fixtures." s.files = Dir.glob("lib/**/*") + %w[CONTRIBUTING.md GETTING_STARTED.md LICENSE NAME.md NEWS.md README.md .yardopts] s.require_path = "lib" s.required_ruby_version = Gem::Requirement.new(">= 2.5.0") s.authors = ["Josh Clayton", "Joe Ferris"] s.email = ["jclayton@thoughtbot.com", "jferris@thoughtbot.com"] s.homepage = "https://github.com/thoughtbot/factory_bot" s.add_dependency("activesupport", ">= 5.0.0") s.add_development_dependency("activerecord") s.add_development_dependency("appraisal") s.add_development_dependency("aruba") s.add_development_dependency("cucumber") s.add_development_dependency("rake") s.add_development_dependency("rspec") s.add_development_dependency("rspec-its") s.add_development_dependency("standard") s.add_development_dependency("simplecov") s.add_development_dependency("yard") s.license = "MIT" end factory_bot-6.2.0/features/000077500000000000000000000000001404526231600156535ustar00rootroot00000000000000factory_bot-6.2.0/features/find_definitions.feature000066400000000000000000000043311404526231600225440ustar00rootroot00000000000000Feature: FactoryBot can find factory definitions correctly Scenario: Find definitions with a path Given a file named "awesome_factories.rb" with: """ FactoryBot.define do factory :awesome_category, :class => Category do name { "awesome!!!" } end end """ When "awesome_factories.rb" is added to FactoryBot's file definitions path And I create a "awesome_category" instance from FactoryBot Then I should find the following for the last category: | name | | awesome!!! | Scenario: Find definitions with an absolute path Given a file named "awesome_factories.rb" with: """ FactoryBot.define do factory :another_awesome_category, :class => Category do name { "awesome!!!" } end end """ When "awesome_factories.rb" is added to FactoryBot's file definitions path as an absolute path And I create a "another_awesome_category" instance from FactoryBot Then I should find the following for the last category: | name | | awesome!!! | Scenario: Find definitions with a folder Given a file named "nested/great_factories.rb" with: """ FactoryBot.define do factory :great_category, :class => Category do name { "great!!!" } end end """ When "nested" is added to FactoryBot's file definitions path And I create a "great_category" instance from FactoryBot Then I should find the following for the last category: | name | | great!!! | Scenario: Reload FactoryBot Given a file named "nested/reload_factories.rb" with: """ FactoryBot.define do sequence(:great) trait :admin do admin { true } end factory :handy_category, :class => Category do name { "handy" } end end """ When "nested" is added to FactoryBot's file definitions path And I append to "nested/reload_factories.rb" with: """ FactoryBot.modify do factory :handy_category do name { "HANDY!!!" } end end """ And I reload factories And I create a "handy_category" instance from FactoryBot Then I should find the following for the last category: | name | | HANDY!!! | factory_bot-6.2.0/features/step_definitions/000077500000000000000000000000001404526231600212215ustar00rootroot00000000000000factory_bot-6.2.0/features/step_definitions/database_steps.rb000066400000000000000000000003341404526231600245300ustar00rootroot00000000000000Then(/^I should find the following for the last category:$/) do |table| table.hashes.first.each do |key, value| expect(Category.last.attributes[key].to_s).to eq value end end Before do Category.delete_all end factory_bot-6.2.0/features/step_definitions/factory_bot_steps.rb000066400000000000000000000020111404526231600252710ustar00rootroot00000000000000module FactoryBotDefinitionsHelper def append_file_to_factory_bot_definitions_path(path_to_file) FactoryBot.definition_file_paths ||= [] FactoryBot.definition_file_paths << path_to_file end end World(FactoryBotDefinitionsHelper) When(/^"([^"]*)" is added to FactoryBot's file definitions path$/) do |file_name| new_factory_file = File.join(expand_path("."), file_name.gsub(".rb", "")) append_file_to_factory_bot_definitions_path(new_factory_file) step %(I find definitions) end When(/^"([^"]*)" is added to FactoryBot's file definitions path as an absolute path$/) do |file_name| new_factory_file = File.expand_path(File.join(expand_path("."), file_name.gsub(".rb", ""))) append_file_to_factory_bot_definitions_path(new_factory_file) step %(I find definitions) end When(/^I create a "([^"]*)" instance from FactoryBot$/) do |factory_name| FactoryBot.create(factory_name) end When(/^I find definitions$/) do FactoryBot.find_definitions end When(/^I reload factories$/) do FactoryBot.reload end factory_bot-6.2.0/features/support/000077500000000000000000000000001404526231600173675ustar00rootroot00000000000000factory_bot-6.2.0/features/support/env.rb000066400000000000000000000003231404526231600205020ustar00rootroot00000000000000PROJECT_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..", "..")) require "simplecov" $: << File.join(PROJECT_ROOT, "lib") require "active_record" require "factory_bot" require "aruba/cucumber" factory_bot-6.2.0/features/support/factories.rb000066400000000000000000000005311404526231600216720ustar00rootroot00000000000000ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) class CreateSchema < ActiveRecord::Migration[5.0] def self.up create_table :categories, force: true do |t| t.string :name end end end CreateSchema.suppress_messages { CreateSchema.migrate(:up) } class Category < ActiveRecord::Base; end factory_bot-6.2.0/gemfiles/000077500000000000000000000000001404526231600156305ustar00rootroot00000000000000factory_bot-6.2.0/gemfiles/5.0.gemfile000066400000000000000000000003721404526231600174660ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", "~> 1.3.6", platforms: [:ruby] gem "activerecord", "~> 5.0.7" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/5.0.gemfile.lock000066400000000000000000000077541404526231600204300ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (5.0.7.2) activesupport (= 5.0.7.2) activerecord (5.0.7.2) activemodel (= 5.0.7.2) activesupport (= 5.0.7.2) arel (~> 7.0) activesupport (5.0.7.2) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.3.0) bundler rake thor (>= 0.14.0) arel (7.1.4) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.3.13) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (1.2.9) thread_safe (~> 0.1) unicode-display_width (2.0.0) yard (0.9.26) PLATFORMS ruby DEPENDENCIES activerecord (~> 5.0.7) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 (~> 1.3.6) standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/gemfiles/5.1.gemfile000066400000000000000000000003561404526231600174710ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", "~> 5.1.7" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/5.1.gemfile.lock000066400000000000000000000077241404526231600204260ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (5.1.7) activesupport (= 5.1.7) activerecord (5.1.7) activemodel (= 5.1.7) activesupport (= 5.1.7) arel (~> 8.0) activesupport (5.1.7) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.3.0) bundler rake thor (>= 0.14.0) arel (8.0.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (1.2.9) thread_safe (~> 0.1) unicode-display_width (2.0.0) yard (0.9.26) PLATFORMS ruby DEPENDENCIES activerecord (~> 5.1.7) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/gemfiles/5.2.gemfile000066400000000000000000000003561404526231600174720ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", "~> 5.2.3" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/5.2.gemfile.lock000066400000000000000000000077401404526231600204250ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (5.2.4.5) activesupport (= 5.2.4.5) activerecord (5.2.4.5) activemodel (= 5.2.4.5) activesupport (= 5.2.4.5) arel (>= 9.0) activesupport (5.2.4.5) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.3.0) bundler rake thor (>= 0.14.0) arel (9.0.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (1.2.9) thread_safe (~> 0.1) unicode-display_width (2.0.0) yard (0.9.26) PLATFORMS ruby DEPENDENCIES activerecord (~> 5.2.3) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/gemfiles/6.0.gemfile000066400000000000000000000003711404526231600174660ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", "~> 60.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", "~> 6.0.0" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/6.0.gemfile.lock000066400000000000000000000100001404526231600204030ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (6.0.3.5) activesupport (= 6.0.3.5) activerecord (6.0.3.5) activemodel (= 6.0.3.5) activesupport (= 6.0.3.5) activesupport (6.0.3.5) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) zeitwerk (~> 2.2, >= 2.2.2) appraisal (2.3.0) bundler rake thor (>= 0.14.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (1.2.9) thread_safe (~> 0.1) unicode-display_width (2.0.0) yard (0.9.26) zeitwerk (2.4.2) PLATFORMS ruby DEPENDENCIES activerecord (~> 6.0.0) activerecord-jdbcsqlite3-adapter (~> 60.0.rc1) appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/gemfiles/6.1.gemfile000066400000000000000000000003711404526231600174670ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", "~> 61.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", "~> 6.1.0" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/6.1.gemfile.lock000066400000000000000000000077561404526231600204340ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: activemodel (6.1.3) activesupport (= 6.1.3) activerecord (6.1.3) activemodel (= 6.1.3) activesupport (= 6.1.3) activesupport (6.1.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) zeitwerk (~> 2.3) appraisal (2.3.0) bundler rake thor (>= 0.14.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (2.0.4) concurrent-ruby (~> 1.0) unicode-display_width (2.0.0) yard (0.9.26) zeitwerk (2.4.2) PLATFORMS ruby DEPENDENCIES activerecord (~> 6.1.0) activerecord-jdbcsqlite3-adapter (~> 60.0.rc1) appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/gemfiles/main.gemfile000066400000000000000000000004501404526231600201050ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", "~> 61.0", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", git: "https://github.com/rails/rails.git", branch: "main" gemspec name: "factory_bot", path: "../" factory_bot-6.2.0/gemfiles/main.gemfile.lock000066400000000000000000000102031404526231600210310ustar00rootroot00000000000000GIT remote: https://github.com/rails/rails.git revision: 146f0e78474cecfb3a25a089efe50c8685739428 branch: main specs: activemodel (7.0.0.alpha) activesupport (= 7.0.0.alpha) activerecord (7.0.0.alpha) activemodel (= 7.0.0.alpha) activesupport (= 7.0.0.alpha) activesupport (7.0.0.alpha) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 1.6, < 2) minitest (>= 5.1) tzinfo (~> 2.0) zeitwerk (~> 2.3) PATH remote: .. specs: factory_bot (6.1.0) activesupport (>= 5.0.0) GEM remote: https://rubygems.org/ specs: appraisal (2.3.0) bundler rake thor (>= 0.14.0) aruba (1.0.4) childprocess (>= 2.0, < 5.0) contracts (~> 0.16.0) cucumber (>= 2.4, < 6.0) rspec-expectations (~> 3.4) thor (~> 1.0) ast (2.4.2) builder (3.2.4) childprocess (4.0.0) concurrent-ruby (1.1.8) contracts (0.16.0) cucumber (5.3.0) builder (~> 3.2, >= 3.2.4) cucumber-core (~> 8.0, >= 8.0.1) cucumber-create-meta (~> 2.0, >= 2.0.2) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-html-formatter (~> 9.0, >= 9.0.0) cucumber-messages (~> 13.1, >= 13.1.0) cucumber-wire (~> 4.0, >= 4.0.1) diff-lcs (~> 1.4, >= 1.4.4) multi_test (~> 0.1, >= 0.1.2) sys-uname (~> 1.2, >= 1.2.1) cucumber-core (8.0.1) cucumber-gherkin (~> 15.0, >= 15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-tag-expressions (~> 2.0, >= 2.0.4) cucumber-create-meta (2.0.4) cucumber-messages (~> 13.1, >= 13.1.0) sys-uname (~> 1.2, >= 1.2.1) cucumber-cucumber-expressions (10.3.0) cucumber-gherkin (15.0.2) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-html-formatter (9.0.0) cucumber-messages (~> 13.0, >= 13.0.1) cucumber-messages (13.2.1) protobuf-cucumber (~> 3.10, >= 3.10.8) cucumber-tag-expressions (2.0.4) cucumber-wire (4.0.1) cucumber-core (~> 8.0, >= 8.0.1) cucumber-cucumber-expressions (~> 10.3, >= 10.3.0) cucumber-messages (~> 13.0, >= 13.0.1) diff-lcs (1.4.4) docile (1.3.5) ffi (1.14.2) i18n (1.8.9) concurrent-ruby (~> 1.0) middleware (0.1.0) minitest (5.14.3) multi_test (0.1.2) parallel (1.20.1) parser (3.0.0.0) ast (~> 2.4.1) protobuf-cucumber (3.10.8) activesupport (>= 3.2) middleware thor thread_safe rainbow (3.0.0) rake (13.0.3) regexp_parser (2.0.3) rexml (3.2.4) rspec (3.10.0) rspec-core (~> 3.10.0) rspec-expectations (~> 3.10.0) rspec-mocks (~> 3.10.0) rspec-core (3.10.1) rspec-support (~> 3.10.0) rspec-expectations (3.10.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.10.2) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.2) rubocop (1.10.0) parallel (~> 1.10) parser (>= 3.0.0.0) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.8, < 3.0) rexml rubocop-ast (>= 1.2.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 3.0) rubocop-ast (1.4.1) parser (>= 2.7.1.5) rubocop-performance (1.9.2) rubocop (>= 0.90.0, < 2.0) rubocop-ast (>= 0.4.0) ruby-progressbar (1.11.0) simplecov (0.21.2) docile (~> 1.1) simplecov-html (~> 0.11) simplecov_json_formatter (~> 0.1) simplecov-html (0.12.3) simplecov_json_formatter (0.1.2) sqlite3 (1.4.2) standard (0.13.0) rubocop (= 1.10.0) rubocop-performance (= 1.9.2) sys-uname (1.2.2) ffi (~> 1.1) thor (1.1.0) thread_safe (0.3.6) tzinfo (2.0.4) concurrent-ruby (~> 1.0) unicode-display_width (2.0.0) yard (0.9.26) zeitwerk (2.4.2) PLATFORMS ruby DEPENDENCIES activerecord! activerecord-jdbcsqlite3-adapter (~> 60.0) appraisal aruba cucumber factory_bot! rake rspec rspec-its simplecov sqlite3 standard yard BUNDLED WITH 2.1.4 factory_bot-6.2.0/lib/000077500000000000000000000000001404526231600146035ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot.rb000066400000000000000000000060001404526231600174370ustar00rootroot00000000000000require "set" 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_calculator" 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" 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/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 # 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 # # Arguments: # * starting_id +Integer+ # The new starting id value. def self.build_stubbed_starting_id=(starting_id) Strategy::Stub.next_id = starting_id - 1 end class << self delegate :factories, :register_strategy, :rewind_sequences, :strategy_by_name, to: Internal end end FactoryBot::Internal.register_default_strategies factory_bot-6.2.0/lib/factory_bot/000077500000000000000000000000001404526231600171165ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/aliases.rb000066400000000000000000000005341404526231600210660ustar00rootroot00000000000000module 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.to_s) attribute.to_s.sub(pattern, replace).to_sym end }.compact << attribute end end factory_bot-6.2.0/lib/factory_bot/attribute.rb000066400000000000000000000007361404526231600214540ustar00rootroot00000000000000require "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 factory_bot-6.2.0/lib/factory_bot/attribute/000077500000000000000000000000001404526231600211215ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/attribute/association.rb000066400000000000000000000011121404526231600237550ustar00rootroot00000000000000module FactoryBot class Attribute # @api private class Association < Attribute attr_reader :factory def initialize(name, factory, overrides) super(name, false) @factory = factory @overrides = overrides end def to_proc factory = @factory overrides = @overrides traits_and_overrides = [factory, overrides].flatten factory_name = traits_and_overrides.shift -> { association(factory_name, *traits_and_overrides) } end def association? true end end end end factory_bot-6.2.0/lib/factory_bot/attribute/dynamic.rb000066400000000000000000000010221404526231600230650ustar00rootroot00000000000000module FactoryBot class Attribute # @api private class Dynamic < Attribute def initialize(name, ignored, block) super(name, ignored) @block = block end def to_proc block = @block -> { value = case block.arity when 1, -1, -2 then instance_exec(self, &block) else instance_exec(&block) end raise SequenceAbuseError if FactoryBot::Sequence === value value } end end end end factory_bot-6.2.0/lib/factory_bot/attribute/sequence.rb000066400000000000000000000005011404526231600232520ustar00rootroot00000000000000module FactoryBot class Attribute # @api private class Sequence < Attribute def initialize(name, sequence, ignored) super(name, ignored) @sequence = sequence end def to_proc sequence = @sequence -> { FactoryBot.generate(sequence) } end end end end factory_bot-6.2.0/lib/factory_bot/attribute_assigner.rb000066400000000000000000000055071404526231600233500ustar00rootroot00000000000000module 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 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 def hash @evaluator.instance = build_hash attributes_to_set_on_hash.each_with_object({}) do |attribute, result| result[attribute] = get(attribute) end end private def method_tracking_evaluator @method_tracking_evaluator ||= Decorator::AttributeHash.new( decorated_evaluator, attribute_names_to_assign ) end def decorated_evaluator Decorator::InvocationTracker.new( Decorator::NewConstructor.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 def attribute_names_to_assign @attribute_names_to_assign ||= non_ignored_attribute_names + override_names - ignored_attribute_names - alias_names_to_ignore 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 hash_instance_methods_to_respond_to @attribute_list.names + override_names + @build_class.instance_methods end def alias_names_to_ignore @attribute_list.non_ignored.flat_map { |attribute| override_names.map do |override| attribute.name if ignorable_alias?(attribute, override) end }.compact end def ignorable_alias?(attribute, override) attribute.alias_for?(override) && attribute.name != override && !ignored_attribute_names.include?(override) end end end factory_bot-6.2.0/lib/factory_bot/attribute_list.rb000066400000000000000000000030511404526231600225000ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/callback.rb000066400000000000000000000011711404526231600211770ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/callbacks_observer.rb000066400000000000000000000007011404526231600232670ustar00rootroot00000000000000module FactoryBot # @api private class CallbacksObserver def initialize(callbacks, evaluator) @callbacks = callbacks @evaluator = evaluator end def update(name, result_instance) callbacks_by_name(name).each do |callback| callback.run(result_instance, @evaluator) end end private def callbacks_by_name(name) @callbacks.select { |callback| callback.name == name } end end end factory_bot-6.2.0/lib/factory_bot/configuration.rb000066400000000000000000000016141404526231600223140ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/declaration.rb000066400000000000000000000006161404526231600217330ustar00rootroot00000000000000require "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 factory_bot-6.2.0/lib/factory_bot/declaration/000077500000000000000000000000001404526231600214035ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/declaration/association.rb000066400000000000000000000026251404526231600242510ustar00rootroot00000000000000module FactoryBot class Declaration # @api private class Association < Declaration def initialize(name, *options) super(name, false) @options = options.dup @overrides = options.extract_options! @factory_name = @overrides.delete(:factory) || name @traits = options end def ==(other) self.class == other.class && name == other.name && options == other.options end protected attr_reader :options private attr_reader :factory_name, :overrides, :traits def build raise_if_arguments_are_declarations! [ Attribute::Association.new( name, factory_name, [traits, overrides].flatten ) ] end def raise_if_arguments_are_declarations! if factory_name.is_a?(Declaration) raise ArgumentError.new(<<~MSG) Association '#{name}' received an invalid factory argument. Did you mean? 'factory: :#{factory_name.name}' MSG end overrides.each do |attribute, value| if value.is_a?(Declaration) raise ArgumentError.new(<<~MSG) Association '#{name}' received an invalid attribute override. Did you mean? '#{attribute}: :#{value.name}' MSG end end end end end end factory_bot-6.2.0/lib/factory_bot/declaration/dynamic.rb000066400000000000000000000010311404526231600233470ustar00rootroot00000000000000module FactoryBot class Declaration # @api private class Dynamic < Declaration def initialize(name, ignored = false, block = nil) super(name, ignored) @block = block end def ==(other) self.class == other.class && name == other.name && ignored == other.ignored && block == other.block end protected attr_reader :block private def build [Attribute::Dynamic.new(name, @ignored, @block)] end end end end factory_bot-6.2.0/lib/factory_bot/declaration/implicit.rb000066400000000000000000000016631404526231600235500ustar00rootroot00000000000000module FactoryBot class Declaration # @api private class Implicit < Declaration def initialize(name, factory = nil, ignored = false) super(name, ignored) @factory = factory end def ==(other) self.class == other.class && name == other.name && factory == other.factory && ignored == other.ignored end protected attr_reader :factory private def build if FactoryBot.factories.registered?(name) [Attribute::Association.new(name, name, {})] elsif FactoryBot::Internal.sequences.registered?(name) [Attribute::Sequence.new(name, name, @ignored)] elsif @factory.name.to_s == name.to_s message = "Self-referencing trait '#{@name}'" raise TraitDefinitionError, message else @factory.inherit_traits([name]) [] end end end end end factory_bot-6.2.0/lib/factory_bot/declaration_list.rb000066400000000000000000000017221404526231600227650ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/decorator.rb000066400000000000000000000017041404526231600214270ustar00rootroot00000000000000module FactoryBot class Decorator < BasicObject undef_method :== def initialize(component) @component = component end if ::Gem::Version.new(::RUBY_VERSION) >= ::Gem::Version.new("2.7") class_eval(<<~RUBY, __FILE__, __LINE__ + 1) def method_missing(...) # rubocop:disable Style/MethodMissingSuper, Style/MissingRespondToMissing @component.send(...) end def send(...) __send__(...) end RUBY else def method_missing(name, *args, &block) # rubocop:disable Style/MethodMissingSuper, Style/MissingRespondToMissing @component.send(name, *args, &block) end def send(symbol, *args, &block) __send__(symbol, *args, &block) end 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 factory_bot-6.2.0/lib/factory_bot/decorator/000077500000000000000000000000001404526231600211005ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/decorator/attribute_hash.rb000066400000000000000000000006031404526231600244320ustar00rootroot00000000000000module FactoryBot class Decorator class AttributeHash < Decorator def initialize(component, attributes = []) super(component) @attributes = attributes end def attributes @attributes.each_with_object({}) do |attribute_name, result| result[attribute_name] = @component.send(attribute_name) end end end end end factory_bot-6.2.0/lib/factory_bot/decorator/disallows_duplicates_registry.rb000066400000000000000000000005141404526231600275730ustar00rootroot00000000000000module FactoryBot class Decorator class DisallowsDuplicatesRegistry < Decorator def register(name, item) if registered?(name) raise DuplicateDefinitionError, "#{@component.name} already registered: #{name}" else @component.register(name, item) end end end end end factory_bot-6.2.0/lib/factory_bot/decorator/invocation_tracker.rb000066400000000000000000000007361404526231600253170ustar00rootroot00000000000000module FactoryBot class Decorator class InvocationTracker < Decorator def initialize(component) super @invoked_methods = [] end def method_missing(name, *args, &block) # rubocop:disable Style/MissingRespondToMissing @invoked_methods << name super end ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true) def __invoked_methods__ @invoked_methods.uniq end end end end factory_bot-6.2.0/lib/factory_bot/decorator/new_constructor.rb000066400000000000000000000003661404526231600246700ustar00rootroot00000000000000module FactoryBot class Decorator class NewConstructor < Decorator def initialize(component, build_class) super(component) @build_class = build_class end delegate :new, to: :@build_class end end end factory_bot-6.2.0/lib/factory_bot/definition.rb000066400000000000000000000105371404526231600216010ustar00rootroot00000000000000module FactoryBot # @api private class Definition attr_reader :defined_traits, :declarations, :name, :registered_enums def initialize(name, base_traits = []) @name = name @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 defined_traits.each do |defined_trait| base_traits.each { |bt| bt.define_trait defined_trait } additional_traits.each { |at| at.define_trait defined_trait } end @compiled = true 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 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 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 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) 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 factory_bot-6.2.0/lib/factory_bot/definition_hierarchy.rb000066400000000000000000000015501404526231600236320ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/definition_proxy.rb000066400000000000000000000156311404526231600230420ustar00rootroot00000000000000module 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, Style/MethodMissingSuper 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) sequence = Sequence.new(name, *args, &block) FactoryBot::Internal.register_inline_sequence(sequence) add_attribute(name) { increment_sequence(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, &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 end end factory_bot-6.2.0/lib/factory_bot/enum.rb000066400000000000000000000011401404526231600204030ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/errors.rb000066400000000000000000000021361404526231600207610ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/evaluation.rb000066400000000000000000000011331404526231600216100ustar00rootroot00000000000000require "observer" module FactoryBot class Evaluation include Observable def initialize(evaluator, attribute_assigner, to_create) @evaluator = evaluator @attribute_assigner = attribute_assigner @to_create = to_create end delegate :object, :hash, to: :@attribute_assigner def create(result_instance) case @to_create.arity when 2 then @to_create[result_instance, @evaluator] else @to_create[result_instance] end end def notify(name, result_instance) changed notify_observers(name, result_instance) end end end factory_bot-6.2.0/lib/factory_bot/evaluator.rb000066400000000000000000000044561404526231600214560ustar00rootroot00000000000000require "active_support/core_ext/hash/except" require "active_support/core_ext/class/attribute" module FactoryBot # @api private class Evaluator class_attribute :attribute_lists private_instance_methods.each do |method| undef_method(method) unless method.match?(/^__|initialize/) end def initialize(build_strategy, overrides = {}) @build_strategy = build_strategy @overrides = overrides @cached_attributes = overrides @instance = nil @overrides.each do |name, value| singleton_class.define_attribute(name) { value } end end def association(factory_name, *traits_and_overrides) overrides = traits_and_overrides.extract_options! strategy_override = overrides.fetch(:strategy) { FactoryBot.use_parent_strategy ? @build_strategy.class : :create } traits_and_overrides += [overrides.except(:strategy)] runner = FactoryRunner.new(factory_name, strategy_override, traits_and_overrides) @build_strategy.association(runner) end attr_accessor :instance def method_missing(method_name, *args, &block) # rubocop:disable Style/MethodMissingSuper, Style/MissingRespondToMissing if @instance.respond_to?(method_name) @instance.send(method_name, *args, &block) else SyntaxRunner.new.send(method_name, *args, &block) end end ruby2_keywords :method_missing if respond_to?(:ruby2_keywords, true) def respond_to_missing?(method_name, _include_private = false) @instance.respond_to?(method_name) || SyntaxRunner.new.respond_to?(method_name) end def __override_names__ @overrides.keys end def increment_sequence(sequence) sequence.next(self) end def self.attribute_list AttributeList.new.tap do |list| attribute_lists.each do |attribute_list| list.apply_attributes attribute_list.to_a end end end def self.define_attribute(name, &block) if instance_methods(false).include?(name) || private_instance_methods(false).include?(name) undef_method(name) end define_method(name) do if @cached_attributes.key?(name) @cached_attributes[name] else @cached_attributes[name] = instance_exec(&block) end end end end end factory_bot-6.2.0/lib/factory_bot/evaluator_class_definer.rb000066400000000000000000000010011404526231600243160ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/factory.rb000066400000000000000000000075711404526231600211240ustar00rootroot00000000000000require "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] @definition = Definition.new(@name, options[:traits] || []) @compiled = false end delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, :defined_traits, :inherit_traits, :append_traits, to: :@definition def build_class @build_class ||= if class_name.is_a? Class class_name else class_name.to_s.camelize.constantize end end def run(build_strategy, overrides, &block) block ||= ->(result) { result } compile strategy = StrategyCalculator.new(build_strategy).strategy.new evaluator = evaluator_class.new(strategy, overrides.symbolize_keys) attribute_assigner = AttributeAssigner.new(evaluator, build_class, &compiled_constructor) evaluation = Evaluation.new(evaluator, attribute_assigner, compiled_to_create) evaluation.add_observer(CallbacksObserver.new(callbacks, evaluator)) strategy.result(evaluation).tap(&block) 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 parent.defined_traits.each { |trait| define_trait(trait) } @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 initialize_copy(source) super @definition = @definition.clone @evaluator_class = nil @hierarchy_class = nil @hierarchy_instance = nil @compiled = false end end end factory_bot-6.2.0/lib/factory_bot/factory_runner.rb000066400000000000000000000014721404526231600225070ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/find_definitions.rb000066400000000000000000000014461404526231600227630ustar00rootroot00000000000000module 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", "test/factories" and "spec/factories". Only the first # existing file will be loaded. 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 factory_bot-6.2.0/lib/factory_bot/internal.rb000066400000000000000000000041451404526231600212630ustar00rootroot00000000000000module 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) 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) traits.find(name) 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 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 end end end factory_bot-6.2.0/lib/factory_bot/linter.rb000066400000000000000000000047721404526231600207520ustar00rootroot00000000000000module 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 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| 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 end end factory_bot-6.2.0/lib/factory_bot/null_factory.rb000066400000000000000000000007141404526231600221460ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/null_object.rb000066400000000000000000000007111404526231600217420ustar00rootroot00000000000000module 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 factory_bot-6.2.0/lib/factory_bot/registry.rb000066400000000000000000000016001404526231600213100ustar00rootroot00000000000000require "active_support/core_ext/hash/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") error = KeyError.new(message) error.set_backtrace(key_error.backtrace) error end end end factory_bot-6.2.0/lib/factory_bot/reload.rb000066400000000000000000000002151404526231600207070ustar00rootroot00000000000000module FactoryBot def self.reload Internal.reset_configuration Internal.register_default_strategies find_definitions end end factory_bot-6.2.0/lib/factory_bot/sequence.rb000066400000000000000000000022561404526231600212600ustar00rootroot00000000000000module FactoryBot # Sequences are defined using sequence within a FactoryBot.define block. # Sequence values are generated using next. # @api private class Sequence attr_reader :name def initialize(name, *args, &proc) @name = name @proc = proc options = args.extract_options! @value = args.first || 1 @aliases = options.fetch(:aliases) { [] } 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 rewind @value.rewind end private def value @value.peek end def increment_value @value.next end class EnumeratorAdapter def initialize(value) @first_value = value @value = value end def peek @value end def next @value = @value.next end def rewind @value = @first_value end end end end factory_bot-6.2.0/lib/factory_bot/strategy/000077500000000000000000000000001404526231600207605ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/strategy/attributes_for.rb000066400000000000000000000003201404526231600243340ustar00rootroot00000000000000module FactoryBot module Strategy class AttributesFor def association(runner) runner.run(:null) end def result(evaluation) evaluation.hash end end end end factory_bot-6.2.0/lib/factory_bot/strategy/build.rb000066400000000000000000000004251404526231600224050ustar00rootroot00000000000000module FactoryBot module Strategy class Build def association(runner) runner.run end def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:after_build, instance) end end end end end factory_bot-6.2.0/lib/factory_bot/strategy/create.rb000066400000000000000000000006471404526231600225570ustar00rootroot00000000000000module FactoryBot module Strategy class Create def association(runner) runner.run end def result(evaluation) 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 end end end factory_bot-6.2.0/lib/factory_bot/strategy/null.rb000066400000000000000000000002251404526231600222560ustar00rootroot00000000000000module FactoryBot module Strategy class Null def association(runner) end def result(evaluation) end end end end factory_bot-6.2.0/lib/factory_bot/strategy/stub.rb000066400000000000000000000053021404526231600222620ustar00rootroot00000000000000module FactoryBot module Strategy class Stub @@next_id = 1000 DISABLED_PERSISTENCE_METHODS = [ :connection, :decrement!, :delete, :destroy!, :destroy, :increment!, :reload, :save!, :save, :toggle!, :touch, :update!, :update, :update_attribute, :update_attributes!, :update_attributes, :update_column, :update_columns ].freeze def self.next_id=(id) @@next_id = id end def association(runner) runner.run(:build_stubbed) end def result(evaluation) evaluation.object.tap do |instance| stub_database_interaction_on_result(instance) set_timestamps(instance) clear_changes_information(instance) evaluation.notify(:after_stub, instance) end end private def next_id @@next_id += 1 end def stub_database_interaction_on_result(result_instance) if has_settable_id?(result_instance) result_instance.id ||= next_id end result_instance.instance_eval do def persisted? true end def new_record? false end def destroyed? nil end DISABLED_PERSISTENCE_METHODS.each do |write_method| define_singleton_method(write_method) do |*args| raise "stubbed models are not allowed to access the database - "\ "#{self.class}##{write_method}(#{args.join(",")})" end end end end def has_settable_id?(result_instance) !result_instance.class.respond_to?(:primary_key) || result_instance.class.primary_key end def clear_changes_information(result_instance) if result_instance.respond_to?(:clear_changes_information) result_instance.clear_changes_information end end def set_timestamps(result_instance) if missing_created_at?(result_instance) result_instance.created_at = Time.current end if missing_updated_at?(result_instance) result_instance.updated_at = Time.current end end def missing_created_at?(result_instance) result_instance.respond_to?(:created_at) && result_instance.respond_to?(:created_at=) && result_instance.created_at.blank? end def missing_updated_at?(result_instance) result_instance.respond_to?(:updated_at) && result_instance.respond_to?(:updated_at=) && result_instance.updated_at.blank? end end end end factory_bot-6.2.0/lib/factory_bot/strategy_calculator.rb000066400000000000000000000007311404526231600235170ustar00rootroot00000000000000module FactoryBot # @api private class StrategyCalculator def initialize(name_or_object) @name_or_object = name_or_object end def strategy if strategy_is_object? @name_or_object else strategy_name_to_object end end private def strategy_is_object? @name_or_object.is_a?(Class) end def strategy_name_to_object FactoryBot::Internal.strategy_by_name(@name_or_object) end end end factory_bot-6.2.0/lib/factory_bot/strategy_syntax_method_registrar.rb000066400000000000000000000034011404526231600263330ustar00rootroot00000000000000module FactoryBot # @api private class StrategySyntaxMethodRegistrar def initialize(strategy_name) @strategy_name = strategy_name end def define_strategy_methods define_singular_strategy_method define_list_strategy_method define_pair_strategy_method end def self.with_index(block, index) if block&.arity == 2 ->(instance) { block.call(instance, index) } else block end end private def define_singular_strategy_method strategy_name = @strategy_name define_syntax_method(strategy_name) do |name, *traits_and_overrides, &block| FactoryRunner.new(name, strategy_name, traits_and_overrides).run(&block) end end def define_list_strategy_method strategy_name = @strategy_name define_syntax_method("#{strategy_name}_list") do |name, amount, *traits_and_overrides, &block| unless amount.respond_to?(:times) raise ArgumentError, "count missing for #{strategy_name}_list" end Array.new(amount) do |i| block_with_index = StrategySyntaxMethodRegistrar.with_index(block, i) send(strategy_name, name, *traits_and_overrides, &block_with_index) end end end def define_pair_strategy_method strategy_name = @strategy_name define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block| Array.new(2) { send(strategy_name, name, *traits_and_overrides, &block) } end end def define_syntax_method(name, &block) FactoryBot::Syntax::Methods.module_exec do if method_defined?(name) || private_method_defined?(name) undef_method(name) end define_method(name, &block) end end end end factory_bot-6.2.0/lib/factory_bot/syntax.rb000066400000000000000000000001671404526231600207750ustar00rootroot00000000000000require "factory_bot/syntax/methods" require "factory_bot/syntax/default" module FactoryBot module Syntax end end factory_bot-6.2.0/lib/factory_bot/syntax/000077500000000000000000000000001404526231600204445ustar00rootroot00000000000000factory_bot-6.2.0/lib/factory_bot/syntax/default.rb000066400000000000000000000031251404526231600224160ustar00rootroot00000000000000module FactoryBot module Syntax module Default include Methods def define(&block) DSL.run(block) end def modify(&block) ModifyDSL.run(block) end class DSL def factory(name, options = {}, &block) factory = Factory.new(name, options) proxy = FactoryBot::DefinitionProxy.new(factory.definition) proxy.instance_eval(&block) if block Internal.register_factory(factory) proxy.child_factories.each do |(child_name, child_options, child_block)| parent_factory = child_options.delete(:parent) || name factory(child_name, child_options.merge(parent: parent_factory), &child_block) end end def sequence(name, *args, &block) Internal.register_sequence(Sequence.new(name, *args, &block)) end def trait(name, &block) Internal.register_trait(Trait.new(name, &block)) end def self.run(block) new.instance_eval(&block) end delegate :after, :before, :callback, :initialize_with, :skip_create, :to_create, to: FactoryBot::Internal end class ModifyDSL def factory(name, _options = {}, &block) factory = Internal.factory_by_name(name) proxy = FactoryBot::DefinitionProxy.new(factory.definition.overridable) proxy.instance_eval(&block) end def self.run(block) new.instance_eval(&block) end end end end extend Syntax::Default end factory_bot-6.2.0/lib/factory_bot/syntax/methods.rb000066400000000000000000000123541404526231600224410ustar00rootroot00000000000000module FactoryBot module Syntax ## This module is a container for all strategy methods provided by ## FactoryBot. This includes all the default strategies provided ({Methods#build}, ## {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as ## well as the complementary *_list and *_pair methods. ## @example singular factory execution ## # basic use case ## build(:completed_order) ## ## # factory yielding its result to a block ## create(:post) do |post| ## create(:comment, post: post) ## end ## ## # factory with attribute override ## attributes_for(:post, title: "I love Ruby!") ## ## # factory with traits and attribute override ## build_stubbed(:user, :admin, :male, name: "John Doe") ## ## @example multiple factory execution ## # basic use case ## build_list(:completed_order, 2) ## create_list(:completed_order, 2) ## ## # factory with attribute override ## attributes_for_list(:post, 4, title: "I love Ruby!") ## ## # factory with traits and attribute override ## build_stubbed_list(:user, 15, :admin, :male, name: "John Doe") module Methods # @!parse FactoryBot::Internal.register_default_strategies # @!method build(name, *traits_and_overrides, &block) # (see #strategy_method) # Builds a registered factory by name. # @return [Object] instantiated object defined by the factory # @!method create(name, *traits_and_overrides, &block) # (see #strategy_method) # Creates a registered factory by name. # @return [Object] instantiated object defined by the factory # @!method build_stubbed(name, *traits_and_overrides, &block) # (see #strategy_method) # Builds a stubbed registered factory by name. # @return [Object] instantiated object defined by the factory # @!method attributes_for(name, *traits_and_overrides, &block) # (see #strategy_method) # Generates a hash of attributes for a registered factory by name. # @return [Hash] hash of attributes for the factory # @!method build_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of built objects defined by the factory # @!method create_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of created objects defined by the factory # @!method build_stubbed_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of stubbed objects defined by the factory # @!method attributes_for_list(name, amount, *traits_and_overrides, &block) # (see #strategy_method_list) # @return [Array] array of attribute hashes for the factory # @!method build_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of built objects defined by the factory # @!method create_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of created objects defined by the factory # @!method build_stubbed_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of stubbed objects defined by the factory # @!method attributes_for_pair(name, *traits_and_overrides, &block) # (see #strategy_method_pair) # @return [Array] pair of attribute hashes for the factory # @!method strategy_method # @!visibility private # @param [Symbol] name the name of the factory to build # @param [Array] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # @!method strategy_method_list # @!visibility private # @param [Symbol] name the name of the factory to execute # @param [Integer] amount the number of instances to execute # @param [Array] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # @!method strategy_method_pair # @!visibility private # @param [Symbol] name the name of the factory to execute # @param [Array] traits_and_overrides splat args traits and a hash of overrides # @param [Proc] block block to be executed # Generates and returns the next value in a sequence. # # Arguments: # name: (Symbol) # The name of the sequence that a value should be generated for. # # Returns: # The next value in the sequence. (Object) def generate(name) Internal.sequence_by_name(name).next end # Generates and returns the list of values in a sequence. # # Arguments: # name: (Symbol) # The name of the sequence that a value should be generated for. # count: (Fixnum) # Count of values # # Returns: # The next value in the sequence. (Object) def generate_list(name, count) (1..count).map do Internal.sequence_by_name(name).next end end end end end factory_bot-6.2.0/lib/factory_bot/syntax_runner.rb000066400000000000000000000001361404526231600223620ustar00rootroot00000000000000module FactoryBot # @api private class SyntaxRunner include Syntax::Methods end end factory_bot-6.2.0/lib/factory_bot/trait.rb000066400000000000000000000012031404526231600205620ustar00rootroot00000000000000module FactoryBot # @api private class Trait attr_reader :name, :definition def initialize(name, &block) @name = name.to_s @block = block @definition = Definition.new(@name) proxy = FactoryBot::DefinitionProxy.new(@definition) if block proxy.instance_eval(&@block) end end delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, :callbacks, :attributes, to: :@definition def names [@name] end def ==(other) name == other.name && block == other.block end protected attr_reader :block end end factory_bot-6.2.0/lib/factory_bot/version.rb000066400000000000000000000000611404526231600211250ustar00rootroot00000000000000module FactoryBot VERSION = "6.2.0".freeze end factory_bot-6.2.0/spec/000077500000000000000000000000001404526231600147675ustar00rootroot00000000000000factory_bot-6.2.0/spec/acceptance/000077500000000000000000000000001404526231600170555ustar00rootroot00000000000000factory_bot-6.2.0/spec/acceptance/activesupport_instrumentation_spec.rb000066400000000000000000000042341404526231600266520ustar00rootroot00000000000000unless 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 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) FactoryBot.define do factory :user do email { "john@example.com" } factory :slow_user do after(:build) { Kernel.sleep(0.1) } 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" 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) 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) end end factory_bot-6.2.0/spec/acceptance/aliases_spec.rb000066400000000000000000000005641404526231600220420ustar00rootroot00000000000000describe "aliases and overrides" do before do FactoryBot.aliases << [/one/, "two"] define_model("User", two: :string, one: :string) FactoryBot.define do factory :user do two { "set value" } end end end subject { FactoryBot.create(:user, one: "override") } its(:one) { should eq "override" } its(:two) { should be_nil } end factory_bot-6.2.0/spec/acceptance/associations_spec.rb000066400000000000000000000077441404526231600231270ustar00rootroot00000000000000describe "associations" do context "when accidentally using an implicit delcaration 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 delcaration 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 factory_bot-6.2.0/spec/acceptance/attribute_aliases_spec.rb000066400000000000000000000017161404526231600241250ustar00rootroot00000000000000describe "attribute aliases" do before 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 end context "assigning an association by foreign key" do subject { FactoryBot.build(:post, user_id: 1) } it "doesn't assign both an association and its foreign key" do expect(subject.user_id).to eq 1 end end context "assigning an association by passing factory" do subject { FactoryBot.create(:post_with_named_user).user } it "assigns attributes correctly" do expect(subject.name).to eq "John Doe" expect(subject.age).to eq 20 end end end factory_bot-6.2.0/spec/acceptance/attribute_existing_on_object_spec.rb000066400000000000000000000033341404526231600263560ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/attributes_for_spec.rb000066400000000000000000000041301404526231600234460ustar00rootroot00000000000000describe "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) 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 factory_bot-6.2.0/spec/acceptance/attributes_from_instance_spec.rb000066400000000000000000000026431404526231600255160ustar00rootroot00000000000000describe "calling methods on the model instance" do before do define_model("User", age: :integer, age_copy: :integer) do def age read_attribute(:age) || 18 end end FactoryBot.define do factory :user do age_copy { age } end end end context "without the attribute being overridden" do it "returns the correct value from the instance" do expect(FactoryBot.build(:user).age_copy).to eq 18 end it "returns nil during attributes_for" do expect(FactoryBot.attributes_for(:user)[:age_copy]).to be_nil end it "doesn't instantiate a record with attributes_for" do allow(User).to receive(:new) FactoryBot.attributes_for(:user) expect(User).to_not have_received(:new) end end context "with the attribute being overridden" do it "uses the overridden value" do expect(FactoryBot.build(:user, age_copy: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryBot.attributes_for(:user, age_copy: 25)[:age_copy]).to eq 25 end end context "with the referenced attribute being overridden" do it "uses the overridden value" do expect(FactoryBot.build(:user, age: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryBot.attributes_for(:user, age: 25)[:age_copy]).to eq 25 end end end factory_bot-6.2.0/spec/acceptance/attributes_ordered_spec.rb000066400000000000000000000026741404526231600243170ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/build_list_spec.rb000066400000000000000000000032461404526231600225530ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/build_spec.rb000066400000000000000000000040461404526231600215170ustar00rootroot00000000000000describe "a built 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 { build(:post) } it { should be_new_record } context "when the :use_parent_strategy config option is set to false" do it "assigns and saves associations" do with_temporary_assignment(FactoryBot, :use_parent_strategy, false) do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end end context "when the :use_parent_strategy config option is set to true" do it "assigns but does not save associations" do with_temporary_assignment(FactoryBot, :use_parent_strategy, true) do expect(subject.user).to be_kind_of(User) expect(subject.user).to be_new_record end end end end describe "a built instance with strategy: :create" 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: :create) end end end subject { build(:post) } it { should 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 "calling `build` 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 built instance" do build(:company, name: "thoughtbot") do |company| expect(company.name).to eq("thoughtbot") end end it "returns the built instance" do expected = nil result = build(:company) { |company| expected = company "hello!" } expect(result).to eq expected end end factory_bot-6.2.0/spec/acceptance/build_stubbed_spec.rb000066400000000000000000000164521404526231600232330ustar00rootroot00000000000000describe "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 eq 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 eq 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 eq 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 eq 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 factory_bot-6.2.0/spec/acceptance/callbacks_spec.rb000066400000000000000000000155131404526231600223400ustar00rootroot00000000000000describe "callbacks" do before do define_model("User", first_name: :string, last_name: :string) FactoryBot.define do factory :user_with_callbacks, class: :user do after(:stub) { |user| user.first_name = "Stubby" } after(:build) { |user| user.first_name = "Buildy" } after(:create) { |user| user.last_name = "Createy" } end factory :user_with_inherited_callbacks, parent: :user_with_callbacks do after(:stub) { |user| user.last_name = "Double-Stubby" } after(:build) { |user| user.first_name = "Child-Buildy" } end end end it "runs the after(:stub) callback when stubbing" do user = FactoryBot.build_stubbed(:user_with_callbacks) expect(user.first_name).to eq "Stubby" end it "runs the after(:build) callback when building" do user = FactoryBot.build(:user_with_callbacks) expect(user.first_name).to eq "Buildy" end it "runs both the after(:build) and after(:create) callbacks when creating" do user = FactoryBot.create(:user_with_callbacks) expect(user.first_name).to eq "Buildy" expect(user.last_name).to eq "Createy" end it "runs both the after(:stub) callback on the factory and the inherited after(:stub) callback" do user = FactoryBot.build_stubbed(:user_with_inherited_callbacks) expect(user.first_name).to eq "Stubby" expect(user.last_name).to eq "Double-Stubby" end it "runs child callback after parent callback" do user = FactoryBot.build(:user_with_inherited_callbacks) expect(user.first_name).to eq "Child-Buildy" end end describe "callbacks using Symbol#to_proc" do before do define_model("User") do def confirmed? !!@confirmed end def confirm! @confirmed = true end end FactoryBot.define do factory :user do after :build, &:confirm! end end end it "runs the callback correctly" do user = FactoryBot.build(:user) expect(user).to be_confirmed end end describe "callbacks using syntax methods without referencing FactoryBot explicitly" do before do define_model("User", first_number: :integer, last_number: :integer) FactoryBot.define do sequence(:sequence_1) sequence(:sequence_2) sequence(:sequence_3) factory :user do after(:stub) { generate(:sequence_3) } after(:build) { |user| user.first_number = generate(:sequence_1) } after(:create) { |user, _evaluator| user.last_number = generate(:sequence_2) } end end end it "works when the callback has no variables" do FactoryBot.build_stubbed(:user) expect(FactoryBot.generate(:sequence_3)).to eq 2 end it "works when the callback has one variable" do expect(FactoryBot.build(:user).first_number).to eq 1 end it "works when the callback has two variables" do expect(FactoryBot.create(:user).last_number).to eq 1 end end describe "custom callbacks" do let(:custom_before) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:before_custom, instance) end end end end let(:custom_after) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:after_custom, instance) end end end end let(:totally_custom) do Class.new do def result(evaluation) evaluation.object.tap do |instance| evaluation.notify(:totally_custom, instance) end end end end before do define_model("User", first_name: :string, last_name: :string) do def name [first_name, last_name].join(" ") end end FactoryBot.register_strategy(:custom_before, custom_before) FactoryBot.register_strategy(:custom_after, custom_after) FactoryBot.register_strategy(:totally_custom, totally_custom) FactoryBot.define do factory :user do first_name { "John" } last_name { "Doe" } before(:custom) { |instance| instance.first_name = "Overridden First" } after(:custom) { |instance| instance.last_name = "Overridden Last" } callback(:totally_custom) do |instance| instance.first_name = "Totally" instance.last_name = "Custom" end end end end it "runs a custom before callback when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.custom_before(:user).name).to eq "Overridden First Doe" end it "runs a custom after callback when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.custom_after(:user).name).to eq "John Overridden Last" end it "runs a custom callback without prepending before or after when the proper strategy executes" do expect(FactoryBot.build(:user).name).to eq "John Doe" expect(FactoryBot.totally_custom(:user).name).to eq "Totally Custom" end end describe "binding a callback to multiple callbacks" do before do define_model("User", name: :string) FactoryBot.define do factory :user do callback(:before_create, :after_stub) do |instance| instance.name = instance.name.upcase end end end end it "binds the callback to creation" do expect(FactoryBot.create(:user, name: "John Doe").name).to eq "JOHN DOE" end it "does not bind the callback to building" do expect(FactoryBot.build(:user, name: "John Doe").name).to eq "John Doe" end it "binds the callback to stubbing" do expect(FactoryBot.build_stubbed(:user, name: "John Doe").name).to eq "JOHN DOE" end end describe "global callbacks" do include FactoryBot::Syntax::Methods before do define_model("User", name: :string) define_model("Company", name: :string) FactoryBot.define do after :build do |object| object.name = case object.class.to_s when "User" then "John Doe" when "Company" then "Acme Suppliers" end end after :create do |object| object.name = "#{object.name}!!!" end trait :awesome do after :build do |object| object.name = "___#{object.name}___" end after :create do |object| object.name = "A#{object.name}Z" end end factory :user do after :build do |user| user.name = user.name.downcase end end factory :company do after :build do |company| company.name = company.name.upcase end end end end it "triggers after build callbacks for all factories" do expect(build(:user).name).to eq "john doe" expect(create(:user).name).to eq "john doe!!!" expect(create(:user, :awesome).name).to eq "A___john doe___!!!Z" expect(build(:company).name).to eq "ACME SUPPLIERS" end end factory_bot-6.2.0/spec/acceptance/create_list_spec.rb000066400000000000000000000055641404526231600227240ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/create_pair_spec.rb000066400000000000000000000012751404526231600226770ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/create_spec.rb000066400000000000000000000050511404526231600216600ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/define_child_before_parent_spec.rb000066400000000000000000000007101404526231600257020ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/defining_methods_inside_a_factory_spec.rb000066400000000000000000000007641404526231600273130ustar00rootroot00000000000000describe "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 end factory_bot-6.2.0/spec/acceptance/definition_camel_string_spec.rb000066400000000000000000000005411404526231600252730ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/definition_spec.rb000066400000000000000000000023071404526231600225460ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/definition_without_block_spec.rb000066400000000000000000000004361404526231600255040ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/enum_traits_spec.rb000066400000000000000000000100161404526231600227440ustar00rootroot00000000000000describe "enum traits" do context "when automatically_define_enum_traits is true" do it "builds traits automatically for model enum field" do define_model("Task", status: :integer) do enum status: {queued: 0, started: 1, finished: 2} end 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("Task", status: :integer) do enum status: {queued: 0, started: 1, finished: 2} end 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("Task", status: :integer) do enum status: {queued: 0, started: 1, finished: 2} end 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("Task", status: :integer) do enum status: {queued: 0, started: 1, finished: 2} end 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 factory_bot-6.2.0/spec/acceptance/global_initialize_with_spec.rb000066400000000000000000000037771404526231600251460ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/global_to_create_spec.rb000066400000000000000000000062501404526231600237040ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/initialize_with_spec.rb000066400000000000000000000137261404526231600236210ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/keyed_by_class_spec.rb000066400000000000000000000005521404526231600233760ustar00rootroot00000000000000describe "finding factories keyed by class instead of symbol" do before do define_model("User") do attr_accessor :name, :email end FactoryBot.define do factory :user end end it "doesn't find the factory" do expect { FactoryBot.create(User) }.to( raise_error(KeyError, /Factory not registered: User/) ) end end factory_bot-6.2.0/spec/acceptance/lint_spec.rb000066400000000000000000000110111404526231600213540ustar00rootroot00000000000000describe "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 "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 `save!'} ) end end end factory_bot-6.2.0/spec/acceptance/modify_factories_spec.rb000066400000000000000000000105631404526231600237470ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/modify_inherited_spec.rb000066400000000000000000000025301404526231600237360ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/nested_attributes_spec.rb000066400000000000000000000015601404526231600241460ustar00rootroot00000000000000describe "association assignment from nested attributes" do before do define_model("Post", title: :string) do has_many :comments accepts_nested_attributes_for :comments end define_model("Comment", post_id: :integer, body: :text) do belongs_to :post end FactoryBot.define do factory :post do comments_attributes { [FactoryBot.attributes_for(:comment), FactoryBot.attributes_for(:comment)] } end factory :comment do sequence(:body) { |n| "Body #{n}" } end end end it "assigns the correct amount of comments" do expect(FactoryBot.create(:post).comments.count).to eq 2 end it "assigns the correct amount of comments when overridden" do post = FactoryBot.create(:post, comments_attributes: [FactoryBot.attributes_for(:comment)]) expect(post.comments.count).to eq 1 end end factory_bot-6.2.0/spec/acceptance/overrides_spec.rb000066400000000000000000000024561404526231600224250ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/parent_spec.rb000066400000000000000000000032241404526231600217060ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/private_attributes_spec.rb000066400000000000000000000005161404526231600243360ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/register_strategies_spec.rb000066400000000000000000000076431404526231600245040ustar00rootroot00000000000000shared_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 factory_bot-6.2.0/spec/acceptance/reload_spec.rb000066400000000000000000000005111404526231600216570ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/sequence_context_spec.rb000066400000000000000000000025031404526231600237700ustar00rootroot00000000000000describe "sequences are evaluated in the correct context" do before do define_class("User") do attr_accessor :id 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" 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" 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 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" end end factory_bot-6.2.0/spec/acceptance/sequence_resetting_spec.rb000066400000000000000000000055121404526231600243130ustar00rootroot00000000000000describe "FactoryBot.rewind_sequences" do include FactoryBot::Syntax::Methods it "resets all sequences back to their starting values" do FactoryBot.define do sequence(:email) { |n| "somebody#{n}@example.com" } sequence(:name, %w[Joe Josh].to_enum) end 2.times do generate(:email) generate(:name) end FactoryBot.rewind_sequences email = generate(:email) name = generate(:name) expect(email).to eq "somebody1@example.com" expect(name).to eq "Joe" end it "resets inline sequences back to their starting value" do define_class("User") { attr_accessor :email } FactoryBot.define do factory :user do sequence(:email) { |n| "somebody#{n}@example.com" } end end build_list(:user, 2) FactoryBot.rewind_sequences user = build(:user) expect(user.email).to eq "somebody1@example.com" end it "does not collide with globally registered factories" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:email) { |n| "global-somebody#{n}@example.com" } factory :user do sequence(:email) { |n| "local-somebody#{n}@example.com" } end end 2.times do generate(:email) end build_list(:user, 2) FactoryBot.rewind_sequences user = build(:user) email = generate(:email) expect(user.email).to eq "local-somebody1@example.com" expect(email).to eq "global-somebody1@example.com" end it "still allows global sequences prefixed with a factory name" do define_class("User") { attr_accessor :email } FactoryBot.define do sequence(:user_email) { |n| "global-somebody#{n}@example.com" } factory :user do sequence(:email) { |n| "local-somebody#{n}@example.com" } end end 2.times do generate(:user_email) end build_list(:user, 2) FactoryBot.rewind_sequences user = build(:user) email = generate(:user_email) expect(user.email).to eq "local-somebody1@example.com" expect(email).to eq "global-somebody1@example.com" end it "allows setting sequences within identically named traits" do define_class("User") { attr_accessor :email } define_class("Person") { attr_accessor :email } FactoryBot.define do factory :user do trait :with_email do sequence(:email) { |n| "user#{n}@example.com" } end end factory :person do trait :with_email do sequence(:email) { |n| "person#{n}@example.com" } end end end build_list(:user, 2, :with_email) build_list(:person, 2, :with_email) FactoryBot.rewind_sequences user = build(:user, :with_email) person = build(:person, :with_email) expect(user.email).to eq "user1@example.com" expect(person.email).to eq "person1@example.com" end end factory_bot-6.2.0/spec/acceptance/sequence_spec.rb000066400000000000000000000036641404526231600222350ustar00rootroot00000000000000describe "sequences" do include FactoryBot::Syntax::Methods it "generates several values in the correct format" do FactoryBot.define do sequence :email do |n| "somebody#{n}@example.com" end end first_value = generate(:email) another_value = generate(:email) expect(first_value).to match(/^somebody\d+@example\.com$/) expect(another_value).to match(/^somebody\d+@example\.com$/) expect(first_value).not_to eq another_value end it "generates sequential numbers if no block is given" do FactoryBot.define do sequence :order end first_value = generate(:order) another_value = generate(:order) expect(first_value).to eq 1 expect(another_value).to eq 2 expect(first_value).not_to eq another_value end it "generates aliases for the sequence that reference the same block" do FactoryBot.define do sequence(:size, aliases: [:count, :length]) { |n| "called-#{n}" } end first_value = generate(:size) second_value = generate(:count) third_value = generate(:length) expect(first_value).to eq "called-1" expect(second_value).to eq "called-2" expect(third_value).to eq "called-3" end it "generates aliases for the sequence that reference the same block and retains value" do FactoryBot.define do sequence(:size, "a", aliases: [:count, :length]) { |n| "called-#{n}" } end first_value = generate(:size) second_value = generate(:count) third_value = generate(:length) expect(first_value).to eq "called-a" expect(second_value).to eq "called-b" expect(third_value).to eq "called-c" end it "generates few values of the sequence" do FactoryBot.define do sequence :email do |n| "somebody#{n}@example.com" end end values = generate_list(:email, 2) expect(values.first).to eq("somebody1@example.com") expect(values.second).to eq("somebody2@example.com") end end factory_bot-6.2.0/spec/acceptance/skip_create_spec.rb000066400000000000000000000005441404526231600227100ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/stub_spec.rb000066400000000000000000000042231404526231600213720ustar00rootroot00000000000000describe "a stubbed 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 { build_stubbed(:post) } it "acts as if it came from the database" do should_not be_new_record end it "assigns associations and acts as if it is saved" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "a stubbed instance overriding strategy" 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 { build_stubbed(:post) } it "acts as if it is saved in the database" do should_not be_new_record end it "assigns associations and acts as if it is saved" do expect(subject.user).to be_kind_of(User) expect(subject.user).not_to be_new_record end end describe "a stubbed instance with no primary key" do it "builds a stubbed instance" do using_model_without_pk do FactoryBot.define do factory :model_without_pk end model = FactoryBot.build_stubbed(:model_without_pk) expect(model).to be_truthy end end it "behaves like a persisted record" do using_model_without_pk do FactoryBot.define do factory :model_without_pk end model = FactoryBot.build_stubbed(:model_without_pk) expect(model).to be_persisted expect(model).not_to be_new_record end end def using_model_without_pk define_class("ModelWithoutPk", ActiveRecord::Base) connection = ActiveRecord::Base.connection begin clear_generated_table("model_without_pks") connection.create_table("model_without_pks", id: false) do |t| t.column :updated_at, :datetime end yield ensure clear_generated_table("model_without_pks") end end end factory_bot-6.2.0/spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb000066400000000000000000000025661404526231600310320ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/acceptance/traits_spec.rb000066400000000000000000000604141404526231600217270ustar00rootroot00000000000000describe "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 factory :great_user do great end factory :even_greater_user do great trait :great do great { "EVEN GREATER!!!" } 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 "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, '#') 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_error( KeyError, <<~MSG.strip Trait not registered: "not_quite" referenced within "user" definition Did you mean? "not_quit" MSG ) 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 " } 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 factory_bot-6.2.0/spec/acceptance/transient_attributes_spec.rb000066400000000000000000000066671404526231600247100ustar00rootroot00000000000000describe "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 factory_bot-6.2.0/spec/factory_bot/000077500000000000000000000000001404526231600173025ustar00rootroot00000000000000factory_bot-6.2.0/spec/factory_bot/aliases_spec.rb000066400000000000000000000016571404526231600222730ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/attribute/000077500000000000000000000000001404526231600213055ustar00rootroot00000000000000factory_bot-6.2.0/spec/factory_bot/attribute/association_spec.rb000066400000000000000000000021711404526231600251610ustar00rootroot00000000000000describe 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. # Ususually 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 factory_bot-6.2.0/spec/factory_bot/attribute/dynamic_spec.rb000066400000000000000000000035131404526231600242720ustar00rootroot00000000000000describe 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. Ususually 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 factory_bot-6.2.0/spec/factory_bot/attribute/sequence_spec.rb000066400000000000000000000007271404526231600244620ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/attribute_list_spec.rb000066400000000000000000000124351404526231600237040ustar00rootroot00000000000000module 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 factory_bot-6.2.0/spec/factory_bot/attribute_spec.rb000066400000000000000000000005621404526231600226470ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/callback_spec.rb000066400000000000000000000015411404526231600223760ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/declaration/000077500000000000000000000000001404526231600215675ustar00rootroot00000000000000factory_bot-6.2.0/spec/factory_bot/declaration/association_spec.rb000066400000000000000000000022661404526231600254500ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/declaration/dynamic_spec.rb000066400000000000000000000030461404526231600245550ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/declaration/implicit_spec.rb000066400000000000000000000054501404526231600247440ustar00rootroot00000000000000describe 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 assocition 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 factory_bot-6.2.0/spec/factory_bot/declaration_list_spec.rb000066400000000000000000000073021404526231600241630ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/decorator/000077500000000000000000000000001404526231600212645ustar00rootroot00000000000000factory_bot-6.2.0/spec/factory_bot/decorator/attribute_hash_spec.rb000066400000000000000000000013161404526231600256320ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/definition_proxy_spec.rb000066400000000000000000000221601404526231600242330ustar00rootroot00000000000000describe 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, "undefined method 'static_attributes_are_gone' in 'broken' factory\n" \ "Did you mean? 'static_attributes_are_gone { \"true\" }'\n" ) 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) end it "creates a new sequence with an overridden starting vaue" 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) 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, &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 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 factory_bot-6.2.0/spec/factory_bot/definition_spec.rb000066400000000000000000000045611404526231600227770ustar00rootroot00000000000000describe 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 { nil } 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 factory_bot-6.2.0/spec/factory_bot/disallows_duplicates_registry_spec.rb000066400000000000000000000016221404526231600270100ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/evaluator_class_definer_spec.rb000066400000000000000000000045301404526231600255260ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/factory_spec.rb000066400000000000000000000237701404526231600223210ustar00rootroot00000000000000describe 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 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", add_observer: true) 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 factory_bot-6.2.0/spec/factory_bot/find_definitions_spec.rb000066400000000000000000000073571404526231600241700ustar00rootroot00000000000000shared_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 factory_bot-6.2.0/spec/factory_bot/internal_spec.rb000066400000000000000000000107221404526231600224570ustar00rootroot00000000000000describe 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) FactoryBot::Internal.register_trait(trait) expect(FactoryBot::Internal.trait_by_name(trait.name)).to eq trait 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 factory_bot-6.2.0/spec/factory_bot/null_factory_spec.rb000066400000000000000000000026371404526231600233520ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/null_object_spec.rb000066400000000000000000000014431404526231600231430ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/registry_spec.rb000066400000000000000000000063331404526231600225160ustar00rootroot00000000000000describe 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_error(KeyError, /Did you mean\? "factory_bot"/) 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 factory_bot-6.2.0/spec/factory_bot/sequence_spec.rb000066400000000000000000000072561404526231600224630ustar00rootroot00000000000000shared_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 "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 "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 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 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 end factory_bot-6.2.0/spec/factory_bot/strategy/000077500000000000000000000000001404526231600211445ustar00rootroot00000000000000factory_bot-6.2.0/spec/factory_bot/strategy/attributes_for_spec.rb000066400000000000000000000007251404526231600255430ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/strategy/build_spec.rb000066400000000000000000000003621404526231600236030ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/strategy/create_spec.rb000066400000000000000000000006771404526231600237600ustar00rootroot00000000000000describe 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 factory_bot-6.2.0/spec/factory_bot/strategy/stub_spec.rb000066400000000000000000000051511404526231600234620ustar00rootroot00000000000000shared_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 factory_bot-6.2.0/spec/factory_bot/strategy_calculator_spec.rb000066400000000000000000000016521404526231600247200ustar00rootroot00000000000000describe FactoryBot::StrategyCalculator do it "returns the class passed when it is instantiated with a class" do strategy = define_class("MyAwesomeClass") calculator = FactoryBot::StrategyCalculator.new(strategy).strategy expect(calculator).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) FactoryBot::StrategyCalculator.new(:build).strategy 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) calculator = FactoryBot::StrategyCalculator.new(:build).strategy expect(calculator).to eq strategy end end factory_bot-6.2.0/spec/factory_bot_spec.rb000066400000000000000000000005511404526231600206420ustar00rootroot00000000000000describe FactoryBot do it "finds a registered strategy" do FactoryBot.register_strategy(:strategy_name, :strategy_class) expect(FactoryBot.strategy_by_name(:strategy_name)) .to eq :strategy_class end describe ".use_parent_strategy" do it "is true by default" do expect(FactoryBot.use_parent_strategy).to be true end end end factory_bot-6.2.0/spec/spec_helper.rb000066400000000000000000000015721404526231600176120ustar00rootroot00000000000000require "rspec" require "rspec/its" require "simplecov" require "factory_bot" if RUBY_ENGINE == "jruby" # Workaround for issue in I18n/JRuby combo. # See https://github.com/jruby/jruby/issues/6547 and # https://github.com/ruby-i18n/i18n/issues/555 require "i18n/backend" require "i18n/backend/simple" end Dir["spec/support/**/*.rb"].each { |f| require File.expand_path(f) } RSpec.configure do |config| config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on a # real object. This is generally recommended, and will default to `true` in # RSpec 4. mocks.verify_partial_doubles = true end config.include DeclarationMatchers config.before do FactoryBot.reload end config.order = :random Kernel.srand config.seed config.example_status_persistence_file_path = "tmp/rspec_examples.txt" end factory_bot-6.2.0/spec/support/000077500000000000000000000000001404526231600165035ustar00rootroot00000000000000factory_bot-6.2.0/spec/support/macros/000077500000000000000000000000001404526231600177675ustar00rootroot00000000000000factory_bot-6.2.0/spec/support/macros/define_constant.rb000066400000000000000000000027431404526231600234650ustar00rootroot00000000000000require "active_record" module DefineConstantMacros def define_class(path, base = Object, &block) const = stub_const(path, Class.new(base)) const.class_eval(&block) if block const end def define_model(name, columns = {}, &block) model = define_class(name, ActiveRecord::Base, &block) create_table(model.table_name) do |table| columns.each do |column_name, type| table.column column_name, type end end model end def create_table(table_name, &block) connection = ActiveRecord::Base.connection begin connection.execute("DROP TABLE IF EXISTS #{table_name}") connection.create_table(table_name, &block) created_tables << table_name connection rescue Exception => e # rubocop:disable Lint/RescueException connection.execute("DROP TABLE IF EXISTS #{table_name}") raise e end end def clear_generated_tables created_tables.each do |table_name| clear_generated_table(table_name) end created_tables.clear end def clear_generated_table(table_name) ActiveRecord::Base .connection .execute("DROP TABLE IF EXISTS #{table_name}") end private def created_tables @created_tables ||= [] end end RSpec.configure do |config| config.include DefineConstantMacros config.before(:all) do ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) end config.after do clear_generated_tables end end factory_bot-6.2.0/spec/support/macros/deprecation.rb000066400000000000000000000003461404526231600226140ustar00rootroot00000000000000require "active_support" RSpec.configure do |config| config.around :example, silence_deprecation: true do |example| with_temporary_assignment(FactoryBot::Deprecation, :silenced, true) do example.run end end end factory_bot-6.2.0/spec/support/macros/temporary_assignment.rb000066400000000000000000000006271404526231600245730ustar00rootroot00000000000000module TemporaryAssignment def with_temporary_assignment(assignee, attribute, temporary_value) original_value = assignee.public_send(attribute) attribute_setter = "#{attribute}=" assignee.public_send(attribute_setter, temporary_value) yield ensure assignee.public_send(attribute_setter, original_value) end end RSpec.configure do |config| config.include TemporaryAssignment end factory_bot-6.2.0/spec/support/matchers/000077500000000000000000000000001404526231600203115ustar00rootroot00000000000000factory_bot-6.2.0/spec/support/matchers/be_about_now.rb000066400000000000000000000001761404526231600233050ustar00rootroot00000000000000RSpec::Matchers.define :be_about_now do match do |actual| expect(actual).to be_within(2.seconds).of(Time.now) end end factory_bot-6.2.0/spec/support/matchers/callback.rb000066400000000000000000000003431404526231600223720ustar00rootroot00000000000000RSpec::Matchers.define :have_callback do |callback_name| match do |instance| instance.callbacks.include?(FactoryBot::Callback.new(callback_name, @block)) end chain :with_block do |block| @block = block end end factory_bot-6.2.0/spec/support/matchers/declaration.rb000066400000000000000000000031251404526231600231240ustar00rootroot00000000000000module DeclarationMatchers def have_dynamic_declaration(name) DeclarationMatcher.new(:dynamic).named(name) end def have_association_declaration(name) DeclarationMatcher.new(:association).named(name) end def have_implicit_declaration(name) DeclarationMatcher.new(:implicit).named(name) end class DeclarationMatcher def initialize(declaration_type) @declaration_type = declaration_type end def matches?(subject) subject.declarations.include?(expected_declaration) end def named(name) @name = name self end def ignored @ignored = true self end def with_value(value) @value = value self end def with_factory(factory) @factory = factory self end def with_options(options) @options = options self end def failure_message [ "expected declarations to include declaration of type #{@declaration_type}", @options ? "with options #{options}" : nil ].compact.join " " end private def expected_declaration case @declaration_type when :dynamic then FactoryBot::Declaration::Dynamic.new(@name, ignored?, @value) when :implicit then FactoryBot::Declaration::Implicit.new(@name, @factory, ignored?) when :association if @options FactoryBot::Declaration::Association.new(@name, options) else FactoryBot::Declaration::Association.new(@name) end end end def ignored? !!@ignored end def options @options || {} end end end factory_bot-6.2.0/spec/support/matchers/delegate.rb000066400000000000000000000021131404526231600224050ustar00rootroot00000000000000RSpec::Matchers.define :delegate do |delegated_method| chain :to do |target_method| @target_method = target_method end chain :as do |method_on_target| @method_on_target = method_on_target end chain :with_arguments do |args| @args = args end match do |instance| @instance = instance @args ||= [] return_value = "stubbed return value" method_on_target = @method_on_target || delegated_method stubbed_target = double("stubbed_target", method_on_target => return_value) allow(@instance).to receive(@target_method).and_return stubbed_target begin @instance.send(delegated_method, *@args) == return_value rescue NoMethodError false end end failure_message do if Class === @instance message = "expected #{@instance.name} " prefix = "." else message = "expected #{@instance.class.name} " prefix = "#" end message << "to delegate #{prefix}#{delegated_method} to #{prefix}#{@target_method}" if @method_on_target message << ".#{@method_on_target}" end message end end factory_bot-6.2.0/spec/support/matchers/trait.rb000066400000000000000000000004041404526231600217570ustar00rootroot00000000000000RSpec::Matchers.define :have_trait do |trait_name| match do |instance| instance.defined_traits.any? do |trait| trait.name == trait_name.to_s && trait.send(:block) == @block end end chain :with_block do |block| @block = block end end factory_bot-6.2.0/spec/support/shared_examples/000077500000000000000000000000001404526231600216475ustar00rootroot00000000000000factory_bot-6.2.0/spec/support/shared_examples/strategy.rb000066400000000000000000000060511404526231600240400ustar00rootroot00000000000000shared_examples_for "strategy without association support" do let(:factory) { double("associate_factory") } let(:attribute) { FactoryBot::Attribute::Association.new(:user, :user, {}) } def association_named(name, overrides) runner = FactoryBot::FactoryRunner.new(name, :build, [overrides]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "returns nil when accessing an association" do expect(association_named(:user, {})).to be_nil end end shared_examples_for "strategy with association support" do |factory_bot_strategy_name| let(:factory) { double("associate_factory") } def association_named(name, strategy, overrides) runner = FactoryBot::FactoryRunner.new(name, strategy, [overrides]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "runs the factory with the correct overrides" do association_named(:author, factory_bot_strategy_name, great: "value") expect(factory).to have_received(:run).with(factory_bot_strategy_name, great: "value") end it "finds the factory with the correct factory name" do association_named(:author, factory_bot_strategy_name, great: "value") expect(FactoryBot::Internal).to have_received(:factory_by_name).with(:author) end end shared_examples_for "strategy with strategy: :build" do |factory_bot_strategy_name| let(:factory) { double("associate_factory") } def association_named(name, overrides) runner = FactoryBot::FactoryRunner.new(name, overrides[:strategy], [overrides.except(:strategy)]) subject.association(runner) end before do allow(FactoryBot::Internal).to receive(:factory_by_name).and_return factory allow(factory).to receive(:compile) allow(factory).to receive(:run) end it "runs the factory with the correct overrides" do association_named(:author, strategy: :build, great: "value") expect(factory).to have_received(:run).with(factory_bot_strategy_name, great: "value") end it "finds the factory with the correct factory name" do association_named(:author, strategy: :build, great: "value") expect(FactoryBot::Internal).to have_received(:factory_by_name).with(:author) end end shared_examples_for "strategy with callbacks" do |*callback_names| let(:result_instance) do define_class("ResultInstance") { attr_accessor :id }.new end let(:evaluation) do double("evaluation", object: result_instance, notify: true, create: nil) end it "runs the callbacks #{callback_names} with the evaluation's object" do subject.result(evaluation) callback_names.each do |name| expect(evaluation).to have_received(:notify).with(name, evaluation.object) end end it "returns the object from the evaluation" do expect(subject.result(evaluation)).to eq evaluation.object end end