pax_global_header00006660000000000000000000000064135452273310014517gustar00rootroot0000000000000052 comment=2e48817badf3c4212697e71faf59c1a9a380dc38 factory_bot-5.1.1/000077500000000000000000000000001354522733100140365ustar00rootroot00000000000000factory_bot-5.1.1/.github/000077500000000000000000000000001354522733100153765ustar00rootroot00000000000000factory_bot-5.1.1/.github/ISSUE_TEMPLATE.md000066400000000000000000000007351354522733100201100ustar00rootroot00000000000000### Steps to reproduce [reproduction script]: https://github.com/thoughtbot/factory_bot/blob/master/.github/REPRODUCTION_SCRIPT.rb ### Expected behavior ### Actual behavior ### System configuration **factory_bot version**: **rails version**: **ruby version**: factory_bot-5.1.1/.github/REPRODUCTION_SCRIPT.rb000066400000000000000000000015371354522733100207320ustar00rootroot00000000000000require "bundler/inline" gemfile(true) do source "https://rubygems.org" git_source(:github) { |repo| "https://github.com/#{repo}.git" } gem "factory_bot", "~> 5.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 create_table :posts, force: true do |t| t.string :body end end class Post < ActiveRecord::Base end FactoryBot.define do factory :post do body { "Post body" } end end class FactoryBotTest < Minitest::Test def test_factory_bot_stuff body_override = "Body override" post = FactoryBot.build(:post, body: body_override) assert_equal post.body, body_override end end factory_bot-5.1.1/.gitignore000066400000000000000000000001501354522733100160220ustar00rootroot00000000000000*.swp test.db factory_girl-*.gem factory_bot-*.gem doc .yardoc coverage .bundle tmp bin .rubocop-https* factory_bot-5.1.1/.hound.yml000066400000000000000000000000451354522733100157530ustar00rootroot00000000000000rubocop: config_file: .rubocop.yml factory_bot-5.1.1/.rspec000066400000000000000000000000601354522733100151470ustar00rootroot00000000000000--format progress --color --require spec_helper factory_bot-5.1.1/.rubocop.yml000066400000000000000000000011521354522733100163070ustar00rootroot00000000000000inherit_from: - https://raw.githubusercontent.com/thoughtbot/guides/master/style/ruby/.rubocop.yml AllCops: TargetRubyVersion: 2.3 Exclude: - 'gemfiles/*' - 'tmp/**/*' Metrics/BlockLength: CountComments: true Max: 25 ExcludedMethods: [] Exclude: - "spec/**/*" - '*.gemspec' Style/SymbolArray: EnforcedStyle: brackets Style/FormatStringToken: Enabled: false # TODO: gradually bring this down to 80 as we fix files # Let's not open a big PR to fix all of these at once - # we can fix gradually if we happen to be editing a file that has a violation Metrics/LineLength: Max: 110 factory_bot-5.1.1/.simplecov000066400000000000000000000001021354522733100160310ustar00rootroot00000000000000SimpleCov.start do add_filter "/spec/" add_filter "/tmp/" end factory_bot-5.1.1/.travis.yml000066400000000000000000000011171354522733100161470ustar00rootroot00000000000000rvm: - 2.3 - 2.4 - 2.5 - 2.6 - jruby-9.2.8.0 - ruby-head before_install: - gem update --system - gem update bundler - gem cleanup bundler install: "bundle install --jobs 8" script: "bundle exec rake" gemfile: - gemfiles/4.2.gemfile - gemfiles/5.0.gemfile - gemfiles/5.1.gemfile - gemfiles/5.2.gemfile - gemfiles/6.0.gemfile matrix: exclude: - rvm: 2.3 gemfile: gemfiles/6.0.gemfile - rvm: 2.4 gemfile: gemfiles/6.0.gemfile fast_finish: true allow_failures: - rvm: ruby-head branches: only: - master sudo: false cache: bundler factory_bot-5.1.1/.yardopts000066400000000000000000000001011354522733100156740ustar00rootroot00000000000000lib/**/*.rb - GETTING_STARTED.md CONTRIBUTING.md NAME.md LICENSE factory_bot-5.1.1/Appraisals000066400000000000000000000014661354522733100160670ustar00rootroot00000000000000appraise "4.2" do gem "activerecord", "~> 4.2.11" gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.25", platforms: [:jruby] gem "sqlite3", "~> 1.3.6", platforms: [:ruby] end appraise "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.rc1", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] end factory_bot-5.1.1/CODE_OF_CONDUCT.md000066400000000000000000000002511354522733100166330ustar00rootroot00000000000000# 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-5.1.1/CONTRIBUTING.md000066400000000000000000000045101354522733100162670ustar00rootroot00000000000000# 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, clean up inconsistent whitespace ) * 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 [Gist][] that includes a stack trace and any details that may be necessary to reproduce the bug, including your gem version, Ruby version, and operating system. Ideally, a bug report should include a pull request with failing specs. [gist]: https://gist.github.com/ ## 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]. 2. [Create a topic branch.][branch] 3. Implement your feature or bug fix. 4. Add, commit, and push your changes. 5. [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. [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/ Inspired by https://github.com/middleman/middleman-heroku/blob/master/CONTRIBUTING.md factory_bot-5.1.1/GETTING_STARTED.md000066400000000000000000001073201354522733100166520ustar00rootroot00000000000000Getting Started =============== Update Your Gemfile ------------------- If you're using Rails: ```ruby gem "factory_bot_rails" ``` If you're *not* using Rails: ```ruby gem "factory_bot" ``` JRuby users: factory_bot works with JRuby starting with 1.6.7.2 (latest stable, as per July 2012). JRuby has to be used in 1.9 mode, for that, use JRUBY_OPTS environment variable: ```bash export JRUBY_OPTS=--1.9 ``` Once your Gemfile is updated, you'll want to update your bundle. 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 ------------------ 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 ``` 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 ``` If the constant is not available (if you are using a Rails engine that waits to load models, for example), you can also pass a symbol or string, which factory_bot will constantize later, once you start building objects: ```ruby # It's OK if Doorkeeper::AccessToken isn't loaded yet factory :access_token, class: "Doorkeeper::AccessToken" ``` 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 ``` It is highly 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. 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 Using factories --------------- 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 ``` 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" ``` Note that objects created with `build_stubbed` cannot be serialized with `Marshal.dump`, since factory_bot defines singleton methods on these objects. 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). 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 author # instead of # association :author, factory: :user title { "How to read a book effectively" } body { "There are five steps involved." } end factory :comment do commenter # instead of # association :commenter, factory: :user 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 -------------------- There may be times where your code can be DRYed up by passing in transient attributes to factories. ```ruby factory :user do transient do rockstar { true } upcased { false } end name { "John Doe#{" - Rockstar" if rockstar}" } email { "#{name.downcase}@example.com" } after(:create) do |user, evaluator| user.name.upcase! if evaluator.upcased end end create(:user, upcased: true).name #=> "JOHN DOE - ROCKSTAR" ``` 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. Within factory_bot's dynamic attributes, you can access transient attributes as you would expect. 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. 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 ----------- 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 ``` You can also assign the parent explicitly: ```ruby factory :post do title { "A title" } end factory :approved_post, parent: :post do approved { true } end ``` 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 ------------ 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 ``` You can also specify a different factory or override attributes: ```ruby factory :post do # ... association :author, factory: :user, last_name: "Writely" end ``` 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 ``` Generating data for a `has_many` relationship is a bit more involved, depending on the amount of flexibility desired, but here's a surefire example of generating associated data. ```ruby FactoryBot.define do # post factory with a `belongs_to` association for the user factory :post do title { "Through the Looking Glass" } user end # user factory without associated posts 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 and available in # attributes on the factory, as well as 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) end end end end ``` This allows us to do: ```ruby create(:user).posts.length # 0 create(:user_with_posts).posts.length # 5 create(:user_with_posts, posts_count: 15).posts.length # 15 ``` 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. Here's an example with two models that are related via `has_and_belongs_to_many`: ```ruby FactoryBot.define do # language factory with a `belongs_to` association for the profile factory :language do title { "Through the Looking Glass" } profile end # profile factory without associated languages factory :profile do name { "John Doe" } # profile_with_languages will create language data after the profile has # been created factory :profile_with_languages do # languages_count is declared as an ignored attribute and available in # attributes on the factory, as well as the callback via the evaluator transient do languages_count { 5 } end # the after(:create) yields two values; the profile instance itself and # the evaluator, which stores all values from the factory, including # ignored attributes; `create_list`'s second argument is the number of # records to create and we make sure the profile is associated properly # to the language after(:create) do |profile, evaluator| create_list(:language, evaluator.languages_count, profiles: [profile]) end end end end ``` This allows us to do: ```ruby create(:profile).languages.length # 0 create(:profile_with_languages).languages.length # 5 create(:profile_with_languages, languages_count: 15).languages.length # 15 ``` 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) ``` 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" ``` Sequences can be used in dynamic attributes: ```ruby factory :invite do invitee { generate(:email) } end ``` 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. 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 ``` You can also override the initial value: ```ruby factory :user do sequence(:email, 1000) { |n| "person#{n}@example.com" } end ``` Without a block, the value will increment itself, starting at its initial value: ```ruby factory :post do sequence(:position) end ``` 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. 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. 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 ``` 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. 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 :male do name { "John Doe" } gender { "Male" } login { "#{name} (M)" } end trait :female do name { "Jane Doe" } gender { "Female" } login { "#{name} (F)" } end trait :admin do admin { true } login { "admin-#{name}" } end factory :male_admin, traits: [:male, :admin] # login will be "admin-John Doe" factory :female_admin, traits: [:admin, :female] # login will be "Jane Doe (F)" end ``` You can also override individual attributes granted by a trait in subclasses. ```ruby factory :user do name { "Friendly User" } login { name } trait :male do name { "John Doe" } gender { "Male" } login { "#{name} (M)" } end factory :brandon do male name { "Brandon" } end end ``` 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 :male do name { "John Doe" } gender { "Male" } end trait :admin do admin { true } end end # creates an admin user with gender "Male" and name "Jon Snow" create(:user, :admin, :male, 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 gender "Male" and name "Jon Snow" create_list(:user, 3, :admin, :male, name: "Jon Snow") ``` 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 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 ``` 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 ``` 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. 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 ``` 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 ``` You can also 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 } gender { "Female" } 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 } gender { "Female" } 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) ``` `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 crazy 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-5.1.1/Gemfile000066400000000000000000000002321354522733100153260ustar00rootroot00000000000000source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gemspec name: "factory_bot" factory_bot-5.1.1/Gemfile.lock000066400000000000000000000061421354522733100162630ustar00rootroot00000000000000PATH remote: . specs: factory_bot (5.1.1) activesupport (>= 4.2.0) GEM remote: https://rubygems.org/ specs: activemodel (5.2.3) activesupport (= 5.2.3) activerecord (5.2.3) activemodel (= 5.2.3) activesupport (= 5.2.3) arel (>= 9.0) activerecord-jdbc-adapter (52.3-java) activerecord (~> 5.2.0) activerecord-jdbcsqlite3-adapter (52.3-java) activerecord-jdbc-adapter (= 52.3) jdbc-sqlite3 (~> 3.8, < 3.30) activesupport (5.2.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.2.0) bundler rake thor (>= 0.14.0) arel (9.0.0) aruba (0.14.10) childprocess (>= 0.6.3, < 1.1.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (1.0.1) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (1.6.0) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.28.0) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.2) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.1) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.16.1) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.4.1) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.20) PLATFORMS java ruby DEPENDENCIES activerecord activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/LICENSE000066400000000000000000000020701354522733100150420ustar00rootroot00000000000000Copyright (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-5.1.1/NAME.md000066400000000000000000000014111354522733100150750ustar00rootroot00000000000000# 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-5.1.1/NEWS.md000066400000000000000000000364001354522733100151370ustar00rootroot00000000000000# News ## 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: top-level methods 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-5.1.1/README.md000066400000000000000000000077301354522733100153240ustar00rootroot00000000000000# factory_bot [![Build Status][ci-image]][ci] [![Code Climate][grade-image]][grade] [![Gem Version][version-image]][version] [![Reviewed by Hound][hound-badge-image]][hound] 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 ----------------------- The factory_bot 5.x series supports MRI Ruby 2.3+. The factory_bot 3.x+ series supports MRI Ruby 1.9. Additionally, factory_bot 3.6+ supports JRuby 1.6.7.2+ while running in 1.9 mode. See [GETTING_STARTED] for more information on configuring the JRuby environment. For versions of Ruby prior to 1.9, please use factory_bot 2.x. 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 now maintained by Josh Clayton. 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-2019 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://presskit.thoughtbot.com/images/thoughtbot-logo-for-readmes.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://travis-ci.org/thoughtbot/factory_bot.svg [ci]: https://travis-ci.org/thoughtbot/factory_bot?branch=master [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-5.1.1/RELEASING.md000066400000000000000000000020241354522733100156670ustar00rootroot00000000000000# Releasing 1. Update version file accordingly and run `bundle install` to update the Gemfile.lock. 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-5.1.1/Rakefile000066400000000000000000000015001354522733100154770ustar00rootroot00000000000000require "rubygems" require "bundler" require "rake" require "yard" require "rspec/core/rake_task" require "cucumber/rake/task" Bundler::GemHelper.install_tasks(name: "factory_bot") desc "Default: run the specs and features." task default: %w(spec:unit spec:acceptance features) 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-5.1.1/cucumber.yml000066400000000000000000000000361354522733100163650ustar00rootroot00000000000000default: -r features features factory_bot-5.1.1/factory_bot.gemspec000066400000000000000000000026221354522733100177200ustar00rootroot00000000000000$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.3.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", ">= 4.2.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("rubocop", "0.54") s.add_development_dependency("simplecov") s.add_development_dependency("yard") s.license = "MIT" end factory_bot-5.1.1/features/000077500000000000000000000000001354522733100156545ustar00rootroot00000000000000factory_bot-5.1.1/features/find_definitions.feature000066400000000000000000000043311354522733100225450ustar00rootroot00000000000000Feature: 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-5.1.1/features/step_definitions/000077500000000000000000000000001354522733100212225ustar00rootroot00000000000000factory_bot-5.1.1/features/step_definitions/database_steps.rb000066400000000000000000000003331354522733100245300ustar00rootroot00000000000000Then /^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-5.1.1/features/step_definitions/factory_bot_steps.rb000066400000000000000000000020041354522733100252740ustar00rootroot00000000000000module 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-5.1.1/features/support/000077500000000000000000000000001354522733100173705ustar00rootroot00000000000000factory_bot-5.1.1/features/support/env.rb000066400000000000000000000003231354522733100205030ustar00rootroot00000000000000PROJECT_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-5.1.1/features/support/factories.rb000066400000000000000000000007301354522733100216740ustar00rootroot00000000000000ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:", ) migration_class = if ActiveRecord::Migration.respond_to?(:[]) ActiveRecord::Migration[4.2] else ActiveRecord::Migration end class CreateSchema < migration_class 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-5.1.1/gemfiles/000077500000000000000000000000001354522733100156315ustar00rootroot00000000000000factory_bot-5.1.1/gemfiles/4.2.gemfile000066400000000000000000000004101354522733100174610ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.25", platforms: [:jruby] gem "sqlite3", "~> 1.3.6", platforms: [:ruby] gem "activerecord", "~> 4.2.11" gemspec name: "factory_bot", path: "../" factory_bot-5.1.1/gemfiles/4.2.gemfile.lock000066400000000000000000000062541354522733100204240ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (5.1.1) activesupport (>= 4.2.0) GEM remote: https://rubygems.org/ specs: activemodel (4.2.11.1) activesupport (= 4.2.11.1) builder (~> 3.1) activerecord (4.2.11.1) activemodel (= 4.2.11.1) activesupport (= 4.2.11.1) arel (~> 6.0) activerecord-jdbc-adapter (1.3.25) activerecord (>= 2.2, < 5.0) activerecord-jdbcsqlite3-adapter (1.3.25) activerecord-jdbc-adapter (~> 1.3.25) jdbc-sqlite3 (>= 3.7.2, < 3.9) activesupport (4.2.11.1) i18n (~> 0.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) appraisal (2.2.0) bundler rake thor (>= 0.14.0) arel (6.0.4) aruba (0.14.10) childprocess (>= 0.6.3, < 1.1.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (1.0.1) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (0.9.5) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.8.11.2) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.2) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.1) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.16.1) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.3.13) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.19) PLATFORMS java ruby DEPENDENCIES activerecord (~> 4.2.11) activerecord-jdbcsqlite3-adapter (~> 1.3.25) appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 (~> 1.3.6) yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/gemfiles/5.0.gemfile000066400000000000000000000003721354522733100174670ustar00rootroot00000000000000# 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-5.1.1/gemfiles/5.0.gemfile.lock000066400000000000000000000062201354522733100204140ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (5.1.1) activesupport (>= 4.2.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) activerecord-jdbc-adapter (50.4-java) activerecord (~> 5.0.0, >= 5.0.3) activerecord-jdbcsqlite3-adapter (50.4-java) activerecord-jdbc-adapter (= 50.4) jdbc-sqlite3 (~> 3.8, < 3.30) activesupport (5.0.7.2) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.2.0) bundler rake thor (>= 0.14.0) arel (7.1.4) aruba (0.14.10) childprocess (>= 0.6.3, < 1.1.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (1.0.1) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (1.6.0) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.28.0) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.2) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.1) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.16.1) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.3.13) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.19) PLATFORMS java ruby DEPENDENCIES activerecord (~> 5.0.7) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 (~> 1.3.6) yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/gemfiles/5.1.gemfile000066400000000000000000000003561354522733100174720ustar00rootroot00000000000000# 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-5.1.1/gemfiles/5.1.gemfile.lock000066400000000000000000000061561354522733100204250ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (5.1.1) activesupport (>= 4.2.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) activerecord-jdbc-adapter (51.4-java) activerecord (~> 5.1.0) activerecord-jdbcsqlite3-adapter (51.4-java) activerecord-jdbc-adapter (= 51.4) jdbc-sqlite3 (~> 3.8, < 3.30) activesupport (5.1.7) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.2.0) bundler rake thor (>= 0.14.0) arel (8.0.0) aruba (0.14.10) childprocess (>= 0.6.3, < 1.1.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (1.0.1) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (1.6.0) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.28.0) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.2) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.1) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.16.1) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.4.1) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.19) PLATFORMS java ruby DEPENDENCIES activerecord (~> 5.1.7) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/gemfiles/5.2.gemfile000066400000000000000000000003561354522733100174730ustar00rootroot00000000000000# 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-5.1.1/gemfiles/5.2.gemfile.lock000066400000000000000000000061561354522733100204260ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (5.1.1) activesupport (>= 4.2.0) GEM remote: https://rubygems.org/ specs: activemodel (5.2.3) activesupport (= 5.2.3) activerecord (5.2.3) activemodel (= 5.2.3) activesupport (= 5.2.3) arel (>= 9.0) activerecord-jdbc-adapter (52.3-java) activerecord (~> 5.2.0) activerecord-jdbcsqlite3-adapter (52.3-java) activerecord-jdbc-adapter (= 52.3) jdbc-sqlite3 (~> 3.8, < 3.30) activesupport (5.2.3) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) appraisal (2.2.0) bundler rake thor (>= 0.14.0) arel (9.0.0) aruba (0.14.10) childprocess (>= 0.6.3, < 1.1.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (1.0.1) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (1.6.0) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.28.0) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.2) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.1) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.16.1) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.4.1) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.19) PLATFORMS java ruby DEPENDENCIES activerecord (~> 5.2.3) activerecord-jdbcsqlite3-adapter appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/gemfiles/6.0.gemfile000066400000000000000000000003751354522733100174730ustar00rootroot00000000000000# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord-jdbcsqlite3-adapter", "~> 60.0.rc1", platforms: [:jruby] gem "sqlite3", platforms: [:ruby] gem "activerecord", "~> 6.0.0" gemspec name: "factory_bot", path: "../" factory_bot-5.1.1/gemfiles/6.0.gemfile.lock000066400000000000000000000062361354522733100204240ustar00rootroot00000000000000PATH remote: .. specs: factory_bot (5.1.1) activesupport (>= 4.2.0) GEM remote: https://rubygems.org/ specs: activemodel (6.0.0) activesupport (= 6.0.0) activerecord (6.0.0) activemodel (= 6.0.0) activesupport (= 6.0.0) activerecord-jdbc-adapter (60.0.rc1-java) activerecord (~> 6.0.0.rc1) activerecord-jdbcsqlite3-adapter (60.0.rc1-java) activerecord-jdbc-adapter (= 60.0.rc1) jdbc-sqlite3 (~> 3.8, < 3.30) activesupport (6.0.0) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) zeitwerk (~> 2.1, >= 2.1.8) appraisal (2.2.0) bundler rake thor (>= 0.14.0) aruba (0.14.11) childprocess (>= 0.6.3, < 3.0.0) contracts (~> 0.9) cucumber (>= 1.3.19) ffi (~> 1.9) rspec-expectations (>= 2.99) thor (~> 0.19) ast (2.4.0) backports (3.15.0) builder (3.2.3) childprocess (2.0.0) rake (< 13.0) concurrent-ruby (1.1.5) contracts (0.16.0) cucumber (3.1.2) builder (>= 2.1.2) cucumber-core (~> 3.2.0) cucumber-expressions (~> 6.0.1) cucumber-wire (~> 0.0.1) diff-lcs (~> 1.3) gherkin (~> 5.1.0) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.2) cucumber-core (3.2.1) backports (>= 3.8.0) cucumber-tag_expressions (~> 1.1.0) gherkin (~> 5.0) cucumber-expressions (6.0.1) cucumber-tag_expressions (1.1.1) cucumber-wire (0.0.1) diff-lcs (1.3) docile (1.3.2) ffi (1.11.1) ffi (1.11.1-java) gherkin (5.1.0) i18n (1.6.0) concurrent-ruby (~> 1.0) jdbc-sqlite3 (3.28.0) json (2.2.0) json (2.2.0-java) minitest (5.11.3) multi_json (1.13.1) multi_test (0.1.2) parallel (1.17.0) parser (2.6.3.0) ast (~> 2.4.0) powerpack (0.1.2) rainbow (3.0.0) rake (12.3.3) rspec (3.8.0) rspec-core (~> 3.8.0) rspec-expectations (~> 3.8.0) rspec-mocks (~> 3.8.0) rspec-core (3.8.2) rspec-support (~> 3.8.0) rspec-expectations (3.8.4) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-its (1.3.0) rspec-core (>= 3.0.0) rspec-expectations (>= 3.0.0) rspec-mocks (3.8.1) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.8.0) rspec-support (3.8.2) rubocop (0.54.0) parallel (~> 1.10) parser (>= 2.5) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) unicode-display_width (~> 1.0, >= 1.0.1) ruby-progressbar (1.10.1) simplecov (0.17.0) docile (~> 1.1) json (>= 1.8, < 3) simplecov-html (~> 0.10.0) simplecov-html (0.10.2) sqlite3 (1.4.1) thor (0.20.3) thread_safe (0.3.6) thread_safe (0.3.6-java) tzinfo (1.2.5) thread_safe (~> 0.1) unicode-display_width (1.6.0) yard (0.9.20) zeitwerk (2.1.9) PLATFORMS java ruby DEPENDENCIES activerecord (~> 6.0.0) activerecord-jdbcsqlite3-adapter (~> 60.0.rc1) appraisal aruba cucumber factory_bot! rake rspec rspec-its rubocop (= 0.54) simplecov sqlite3 yard BUNDLED WITH 2.0.2 factory_bot-5.1.1/lib/000077500000000000000000000000001354522733100146045ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot.rb000066400000000000000000000076141354522733100174540ustar00rootroot00000000000000require "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/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/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" require "factory_bot/internal" module FactoryBot Deprecation = ActiveSupport::Deprecation.new("6.0", "factory_bot") def self.configuration Internal.configuration end def self.reset_configuration Internal.reset_configuration end mattr_accessor :use_parent_strategy, instance_accessor: false self.use_parent_strategy = 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 class << self delegate :callbacks, :callback_names, :constructor, :factories, :initialize_with, :sequences, :skip_create, :strategies, :to_create, :traits, to: :configuration delegate :factory_by_name, :register_callback, :register_default_callbacks, :register_default_strategies, :register_factory, :register_sequence, :register_strategy, :register_trait, :rewind_sequences, :sequence_by_name, :strategy_by_name, :trait_by_name, to: Internal attr_accessor :allow_class_lookup deprecate :allow_class_lookup, :allow_class_lookup=, :callback_names, :factory_by_name, :register_callback, :register_default_callbacks, :register_default_strategies, :register_factory, :register_trait, :sequence_by_name, :sequences, :strategies, :trait_by_name, :traits, deprecator: Deprecation end end FactoryBot::Internal.register_default_strategies FactoryBot::Internal.register_default_callbacks factory_bot-5.1.1/lib/factory_bot/000077500000000000000000000000001354522733100171175ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/aliases.rb000066400000000000000000000005401354522733100210640ustar00rootroot00000000000000module FactoryBot class << self attr_accessor :aliases end self.aliases = [ [/(.+)_id/, '\1'], [/(.*)/, '\1_id'], ] def self.aliases_for(attribute) aliases.map do |(pattern, replace)| if pattern.match(attribute.to_s) attribute.to_s.sub(pattern, replace).to_sym end end.compact << attribute end end factory_bot-5.1.1/lib/factory_bot/attribute.rb000066400000000000000000000007361354522733100214550ustar00rootroot00000000000000require "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-5.1.1/lib/factory_bot/attribute/000077500000000000000000000000001354522733100211225ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/attribute/association.rb000066400000000000000000000011161354522733100237620ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/attribute/dynamic.rb000066400000000000000000000010251354522733100230710ustar00rootroot00000000000000module 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 then instance_exec(self, &block) else instance_exec(&block) end raise SequenceAbuseError if FactoryBot::Sequence === value value } end end end end factory_bot-5.1.1/lib/factory_bot/attribute/sequence.rb000066400000000000000000000005011354522733100232530ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/attribute_assigner.rb000066400000000000000000000055771354522733100233600ustar00rootroot00000000000000module 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.reduce({}) do |result, attribute| result[attribute] = get(attribute) result 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 do |attribute| override_names.map do |override| attribute.name if ignorable_alias?(attribute, override) end 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-5.1.1/lib/factory_bot/attribute_list.rb000066400000000000000000000030571354522733100225070ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/callback.rb000066400000000000000000000016751354522733100212110ustar00rootroot00000000000000module FactoryBot class Callback attr_reader :name def initialize(name, block) @name = name.to_sym @block = block ensure_valid_callback_name! end def run(instance, evaluator) case block.arity when 1, -1 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 ensure_valid_callback_name! unless FactoryBot::Internal.callback_names.include?(name) raise InvalidCallbackNameError, "#{name} is not a valid callback name. " + "Valid callback names are #{FactoryBot::Internal.callback_names.inspect}" end end def syntax_runner @syntax_runner ||= SyntaxRunner.new end end end factory_bot-5.1.1/lib/factory_bot/callbacks_observer.rb000066400000000000000000000007011354522733100232700ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/configuration.rb000066400000000000000000000016471354522733100223230ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/declaration.rb000066400000000000000000000006211354522733100217300ustar00rootroot00000000000000require "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-5.1.1/lib/factory_bot/declaration/000077500000000000000000000000001354522733100214045ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/declaration/association.rb000066400000000000000000000020051354522733100242420ustar00rootroot00000000000000module FactoryBot class Declaration # @api private class Association < Declaration def initialize(name, *options) super(name, false) @options = options.dup @overrides = options.extract_options! @traits = options end def ==(other) self.class == other.class && name == other.name && options == other.options end protected attr_reader :options private def build ensure_factory_is_not_a_declaration! factory_name = @overrides[:factory] || name [Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)] end def ensure_factory_is_not_a_declaration! if @overrides[:factory].is_a?(Declaration) raise ArgumentError.new(<<~MSG) Association '#{name}' received an invalid factory argument. Did you mean? 'factory: :#{@overrides[:factory].name}' MSG end end end end end factory_bot-5.1.1/lib/factory_bot/declaration/dynamic.rb000066400000000000000000000010311354522733100233500ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/declaration/implicit.rb000066400000000000000000000016631354522733100235510ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/declaration_list.rb000066400000000000000000000017331354522733100227700ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/decorator.rb000066400000000000000000000010551354522733100214270ustar00rootroot00000000000000module FactoryBot class Decorator < BasicObject undef_method :== def initialize(component) @component = component end def method_missing(name, *args, &block) # rubocop:disable Style/MethodMissing @component.send(name, *args, &block) end def respond_to_missing?(name, include_private = false) @component.respond_to?(name, true) || super end def send(symbol, *args, &block) __send__(symbol, *args, &block) end def self.const_missing(name) ::Object.const_get(name) end end end factory_bot-5.1.1/lib/factory_bot/decorator/000077500000000000000000000000001354522733100211015ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/decorator/attribute_hash.rb000066400000000000000000000006031354522733100244330ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/decorator/disallows_duplicates_registry.rb000066400000000000000000000005141354522733100275740ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/decorator/invocation_tracker.rb000066400000000000000000000006111354522733100253100ustar00rootroot00000000000000module FactoryBot class Decorator class InvocationTracker < Decorator def initialize(component) super @invoked_methods = [] end def method_missing(name, *args, &block) # rubocop:disable Style/MethodMissing @invoked_methods << name super end def __invoked_methods__ @invoked_methods.uniq end end end end factory_bot-5.1.1/lib/factory_bot/decorator/new_constructor.rb000066400000000000000000000003661354522733100246710ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/definition.rb000066400000000000000000000063231354522733100216000ustar00rootroot00000000000000module FactoryBot # @api private class Definition attr_reader :defined_traits, :declarations, :name def initialize(name, base_traits = []) @name = name @declarations = DeclarationList.new(name) @callbacks = [] @defined_traits = Set.new @to_create = nil @base_traits = base_traits @additional_traits = [] @constructor = nil @attributes = nil @compiled = 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_given? @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 unless @compiled declarations.attributes defined_traits.each do |defined_trait| base_traits.each { |bt| bt.define_trait defined_trait } additional_traits.each { |bt| bt.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 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| FactoryBot::Internal.register_callback(name) add_callback(Callback.new(name, block)) end end private def base_traits @base_traits.map { |name| trait_by_name(name) } 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 end end factory_bot-5.1.1/lib/factory_bot/definition_hierarchy.rb000066400000000000000000000017151354522733100236360ustar00rootroot00000000000000module FactoryBot class DefinitionHierarchy def callbacks FactoryBot.callbacks end def constructor FactoryBot.constructor end def to_create FactoryBot.to_create end 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-5.1.1/lib/factory_bot/definition_proxy.rb000066400000000000000000000126521354522733100230430ustar00rootroot00000000000000module 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/MethodMissing 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 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-5.1.1/lib/factory_bot/errors.rb000066400000000000000000000021361354522733100207620ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/evaluation.rb000066400000000000000000000011331354522733100216110ustar00rootroot00000000000000require "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-5.1.1/lib/factory_bot/evaluator.rb000066400000000000000000000043601354522733100214510ustar00rootroot00000000000000require "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 =~ /^__|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) do FactoryBot.use_parent_strategy ? @build_strategy.class : :create end traits_and_overrides += [overrides.except(:strategy)] runner = FactoryRunner.new(factory_name, strategy_override, traits_and_overrides) @build_strategy.association(runner) end def instance=(object_instance) @instance = object_instance end def method_missing(method_name, *args, &block) # rubocop:disable Style/MethodMissing if @instance.respond_to?(method_name) @instance.send(method_name, *args, &block) else SyntaxRunner.new.send(method_name, *args, &block) end end 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-5.1.1/lib/factory_bot/evaluator_class_definer.rb000066400000000000000000000010031354522733100243210ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/factory.rb000066400000000000000000000077521354522733100211260ustar00rootroot00000000000000require "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_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-5.1.1/lib/factory_bot/factory_runner.rb000066400000000000000000000015021354522733100225020ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/find_definitions.rb000066400000000000000000000014461354522733100227640ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/internal.rb000066400000000000000000000045771354522733100212750ustar00rootroot00000000000000module FactoryBot # @api private module Internal DEFAULT_STRATEGIES = { build: FactoryBot::Strategy::Build, create: FactoryBot::Strategy::Create, attributes_for: FactoryBot::Strategy::AttributesFor, build_stubbed: FactoryBot::Strategy::Stub, null: FactoryBot::Strategy::Null, }.freeze DEFAULT_CALLBACKS = [ :after_create, :after_build, :after_stub, :after_create ].freeze class << self delegate :callback_names, :factories, :inline_sequences, :sequences, :strategies, :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 DEFAULT_STRATEGIES.each { |name, klass| register_strategy(name, klass) } end def register_default_callbacks DEFAULT_CALLBACKS.each(&method(:register_callback)) end def register_callback(name) name = name.to_sym callback_names << name end end end end factory_bot-5.1.1/lib/factory_bot/linter.rb000066400000000000000000000051401354522733100207410ustar00rootroot00000000000000module 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.reduce(Hash.new([])) do |result, factory| errors = lint(factory) result[factory] |= errors unless errors.empty? result 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 StandardError => error result |= [FactoryError.new(error, factory)] end result end def lint_traits(factory) result = [] factory.definition.defined_traits.map(&:name).each do |trait_name| begin FactoryBot.public_send(factory_strategy, factory.name, trait_name) rescue StandardError => error result |= [FactoryTraitError.new(error, factory, trait_name)] end end result end def error_message lines = invalid_factories.map do |_factory, exceptions| exceptions.map(&error_message_type) end.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-5.1.1/lib/factory_bot/null_factory.rb000066400000000000000000000006661354522733100221550ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/null_object.rb000066400000000000000000000007471354522733100217540ustar00rootroot00000000000000module 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) if respond_to?(name) nil else super end end def respond_to?(method, _include_private = false) @methods_to_respond_to.include? method.to_s end def respond_to_missing?(*) false end end end factory_bot-5.1.1/lib/factory_bot/registry.rb000066400000000000000000000016111354522733100213130ustar00rootroot00000000000000require "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 => key_error raise key_error_with_custom_message(key_error) end alias :[] :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-5.1.1/lib/factory_bot/reload.rb000066400000000000000000000002651354522733100207150ustar00rootroot00000000000000module FactoryBot def self.reload Internal.reset_configuration Internal.register_default_strategies Internal.register_default_callbacks find_definitions end end factory_bot-5.1.1/lib/factory_bot/sequence.rb000066400000000000000000000022641354522733100212600ustar00rootroot00000000000000module 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) { [] } if !@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-5.1.1/lib/factory_bot/strategy/000077500000000000000000000000001354522733100207615ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/strategy/attributes_for.rb000066400000000000000000000003201354522733100243350ustar00rootroot00000000000000module FactoryBot module Strategy class AttributesFor def association(runner) runner.run(:null) end def result(evaluation) evaluation.hash end end end end factory_bot-5.1.1/lib/factory_bot/strategy/build.rb000066400000000000000000000004251354522733100224060ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/strategy/create.rb000066400000000000000000000006471354522733100225600ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/strategy/null.rb000066400000000000000000000002131354522733100222540ustar00rootroot00000000000000module FactoryBot module Strategy class Null def association(runner); end def result(evaluation); end end end end factory_bot-5.1.1/lib/factory_bot/strategy/stub.rb000066400000000000000000000052051354522733100222650ustar00rootroot00000000000000module 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 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-5.1.1/lib/factory_bot/strategy_calculator.rb000066400000000000000000000007311354522733100235200ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/strategy_syntax_method_registrar.rb000066400000000000000000000027531354522733100263450ustar00rootroot00000000000000module 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 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) { send(strategy_name, name, *traits_and_overrides, &block) } 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-5.1.1/lib/factory_bot/syntax.rb000066400000000000000000000001671354522733100207760ustar00rootroot00000000000000require "factory_bot/syntax/methods" require "factory_bot/syntax/default" module FactoryBot module Syntax end end factory_bot-5.1.1/lib/factory_bot/syntax/000077500000000000000000000000001354522733100204455ustar00rootroot00000000000000factory_bot-5.1.1/lib/factory_bot/syntax/default.rb000066400000000000000000000034751354522733100224270ustar00rootroot00000000000000module 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_given? 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 to_create(&block) FactoryBot.to_create(&block) end def skip_create FactoryBot.skip_create end def initialize_with(&block) FactoryBot.initialize_with(&block) end def self.run(block) new.instance_eval(&block) end delegate :before, :after, :callback, to: :configuration private def configuration Internal.configuration end 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-5.1.1/lib/factory_bot/syntax/methods.rb000066400000000000000000000123541354522733100224420ustar00rootroot00000000000000module 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-5.1.1/lib/factory_bot/syntax_runner.rb000066400000000000000000000001361354522733100223630ustar00rootroot00000000000000module FactoryBot # @api private class SyntaxRunner include Syntax::Methods end end factory_bot-5.1.1/lib/factory_bot/trait.rb000066400000000000000000000012211354522733100205630ustar00rootroot00000000000000module 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_given? 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-5.1.1/lib/factory_bot/version.rb000066400000000000000000000000611354522733100211260ustar00rootroot00000000000000module FactoryBot VERSION = "5.1.1".freeze end factory_bot-5.1.1/spec/000077500000000000000000000000001354522733100147705ustar00rootroot00000000000000factory_bot-5.1.1/spec/acceptance/000077500000000000000000000000001354522733100170565ustar00rootroot00000000000000factory_bot-5.1.1/spec/acceptance/activesupport_instrumentation_spec.rb000066400000000000000000000042341354522733100266530ustar00rootroot00000000000000unless 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-5.1.1/spec/acceptance/aliases_spec.rb000066400000000000000000000005641354522733100220430ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/associations_spec.rb000066400000000000000000000010201354522733100231050ustar00rootroot00000000000000describe "associations" do context "when accidentally using an implicit delcaration for the factory" do it "raises an error about the trait not being registered" 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 end factory_bot-5.1.1/spec/acceptance/attribute_aliases_spec.rb000066400000000000000000000017161354522733100241260ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/attribute_existing_on_object_spec.rb000066400000000000000000000034071354522733100263600ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/attributes_for_spec.rb000066400000000000000000000041401354522733100234500ustar00rootroot00000000000000describe "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) do |attributes| expected = attributes "hello!" end 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-5.1.1/spec/acceptance/attributes_from_instance_spec.rb000066400000000000000000000026431354522733100255170ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/attributes_ordered_spec.rb000066400000000000000000000027171354522733100243160ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/build_list_spec.rb000066400000000000000000000024541354522733100225540ustar00rootroot00000000000000describe "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 end factory_bot-5.1.1/spec/acceptance/build_spec.rb000066400000000000000000000040511354522733100215140ustar00rootroot00000000000000describe "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) do |company| expected = company "hello!" end expect(result).to eq expected end end factory_bot-5.1.1/spec/acceptance/build_stubbed_spec.rb000066400000000000000000000156371354522733100232400ustar00rootroot00000000000000describe "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) do |company| expected = company "hello!" end 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 do build_stubbed(:thing_without_timestamp, updated_at: Time.now) end.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 factory_bot-5.1.1/spec/acceptance/callbacks_spec.rb000066400000000000000000000155461354522733100223470ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/create_list_spec.rb000066400000000000000000000050021354522733100227100ustar00rootroot00000000000000describe "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 "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-5.1.1/spec/acceptance/create_pair_spec.rb000066400000000000000000000012751354522733100227000ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/create_spec.rb000066400000000000000000000050541354522733100216640ustar00rootroot00000000000000describe "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) do |company| expected = company "hello!" end expect(result).to eq expected end end factory_bot-5.1.1/spec/acceptance/define_child_before_parent_spec.rb000066400000000000000000000007101354522733100257030ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/defining_methods_inside_a_factory_spec.rb000066400000000000000000000007651354522733100273150ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/definition_camel_string_spec.rb000066400000000000000000000005411354522733100252740ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/definition_spec.rb000066400000000000000000000023061354522733100225460ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/definition_without_block_spec.rb000066400000000000000000000004361354522733100255050ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/global_initialize_with_spec.rb000066400000000000000000000037771354522733100251470ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/global_to_create_spec.rb000066400000000000000000000062501354522733100237050ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/initialize_with_spec.rb000066400000000000000000000130561354522733100236160ustar00rootroot00000000000000describe "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 factory_bot-5.1.1/spec/acceptance/keyed_by_class_spec.rb000066400000000000000000000005531354522733100234000ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/lint_spec.rb000066400000000000000000000110451354522733100213640ustar00rootroot00000000000000describe "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 do FactoryBot.lint end.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 do only_valid_factories = FactoryBot.factories.reject do |factory| factory.name =~ /invalid/ end FactoryBot.lint only_valid_factories end.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 do FactoryBot.lint traits: true end.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 do FactoryBot.lint traits: true end.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 do FactoryBot.lint traits: false FactoryBot.lint end.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 do FactoryBot.lint strategy: :build end.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 do FactoryBot.lint traits: true, strategy: :build end.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 do FactoryBot.lint(verbose: true) end.to raise_error( FactoryBot::InvalidFactoryError, %r{#{__FILE__}:\d*:in `save!'}, ) end end end factory_bot-5.1.1/spec/acceptance/modify_factories_spec.rb000066400000000000000000000106371354522733100237520ustar00rootroot00000000000000describe "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 do FactoryBot.define { factory :user } end.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-5.1.1/spec/acceptance/modify_inherited_spec.rb000066400000000000000000000025341354522733100237430ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/nested_attributes_spec.rb000066400000000000000000000015601354522733100241470ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/overrides_spec.rb000066400000000000000000000025031354522733100224170ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/parent_spec.rb000066400000000000000000000033371354522733100217140ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/private_attributes_spec.rb000066400000000000000000000005211354522733100243330ustar00rootroot00000000000000describe "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 do FactoryBot.build(:user) end.to raise_error NoMethodError, /foo=/ end end factory_bot-5.1.1/spec/acceptance/register_strategies_spec.rb000066400000000000000000000076431354522733100245050ustar00rootroot00000000000000shared_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-5.1.1/spec/acceptance/reload_spec.rb000066400000000000000000000005111354522733100216600ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/sequence_context_spec.rb000066400000000000000000000025031354522733100237710ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/sequence_resetting_spec.rb000066400000000000000000000055121354522733100243140ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/sequence_spec.rb000066400000000000000000000036661354522733100222400ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/skip_create_spec.rb000066400000000000000000000005441354522733100227110ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/stub_spec.rb000066400000000000000000000042231354522733100213730ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb000066400000000000000000000025661354522733100310330ustar00rootroot00000000000000describe "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-5.1.1/spec/acceptance/traits_spec.rb000066400000000000000000000564621354522733100217400ustar00rootroot00000000000000describe "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_without_admin_scoping, class: User do admin_trait end 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 "factory outside of scope" do subject { FactoryBot.create(:user_without_admin_scoping) } it "raises an error" do expect { subject }. to raise_error(KeyError, "Trait not registered: \"admin_trait\"") end 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 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 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-5.1.1/spec/acceptance/transient_attributes_spec.rb000066400000000000000000000067361354522733100247060ustar00rootroot00000000000000describe "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-5.1.1/spec/factory_bot/000077500000000000000000000000001354522733100173035ustar00rootroot00000000000000factory_bot-5.1.1/spec/factory_bot/aliases_spec.rb000066400000000000000000000014271354522733100222670ustar00rootroot00000000000000describe FactoryBot, "aliases" do context "aliases for an attribute" do subject { FactoryBot.aliases_for(:test) } it { should include(:test) } it { should include(:test_id) } end context "aliases for a foreign key" do subject { FactoryBot.aliases_for(:test_id) } it { should include(:test) } it { should include(:test_id) } end context "aliases for an attribute starting with an underscore" do subject { FactoryBot.aliases_for(:_id) } it { should_not include(:id) } end end describe FactoryBot, "after defining an alias" do before do FactoryBot.aliases << [/(.*)_suffix/, '\1'] end subject { FactoryBot.aliases_for(:test_suffix) } it { should include(:test) } it { should include(:test_suffix_id) } end factory_bot-5.1.1/spec/factory_bot/attribute/000077500000000000000000000000001354522733100213065ustar00rootroot00000000000000factory_bot-5.1.1/spec/factory_bot/attribute/association_spec.rb000066400000000000000000000022011354522733100251540ustar00rootroot00000000000000describe 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) } module MissingMethods def association(*args); end end before do # Define an '#association' instance method allowing it to be mocked. # Ususually this is determined via '#method_missing' subject.extend(MissingMethods) 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-5.1.1/spec/factory_bot/attribute/dynamic_spec.rb000066400000000000000000000034751354522733100243020ustar00rootroot00000000000000describe 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" } module MissingMethods def attribute_defined_on_attribute(*args); end end before do # Define an '#attribute_defined_on_attribute' instance method allowing it # be mocked. Ususually this is determined via '#method_missing' subject.extend(MissingMethods) 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-5.1.1/spec/factory_bot/attribute/sequence_spec.rb000066400000000000000000000007461354522733100244640ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/attribute_list_spec.rb000066400000000000000000000122331354522733100237010ustar00rootroot00000000000000describe 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) subject.define_attribute(attribute) expect(subject.to_a).to eq [attribute] subject.define_attribute(another_attribute) expect(subject.to_a).to eq [attribute, another_attribute] end it "returns the attribute" do attribute = double(:attribute, name: :attribute_name) expect(subject.define_attribute(attribute)).to eq attribute end it "raises if an attribute has already been defined" do attribute = double(:attribute, name: :attribute_name) expect do 2.times { subject.define_attribute(attribute) } end.to raise_error( FactoryBot::AttributeDefinitionError, "Attribute already defined: attribute_name", ) end end describe FactoryBot::AttributeList, "#define_attribute with a named attribute list" do subject { FactoryBot::AttributeList.new(:author) } let(:association_with_same_name) { FactoryBot::Attribute::Association.new(:author, :author, {}) } let(:association_with_different_name) { FactoryBot::Attribute::Association.new(:author, :post, {}) } it "raises when the attribute is a self-referencing association" do expect do subject.define_attribute(association_with_same_name) end.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 expect { subject.define_attribute(association_with_different_name) }.to_not raise_error end end describe FactoryBot::AttributeList, "#apply_attributes" do def list(*attributes) FactoryBot::AttributeList.new.tap do |list| attributes.each { |attribute| list.define_attribute(attribute) } end end it "adds attributes in the order defined" do attribute1 = double(:attribute1, name: :attribute1) attribute2 = double(:attribute2, name: :attribute2) attribute3 = double(:attribute3, name: :attribute3) subject.define_attribute(attribute1) subject.apply_attributes(list(attribute2, attribute3)) expect(subject.to_a).to eq [attribute1, attribute2, attribute3] end end describe FactoryBot::AttributeList, "#associations" do let(:email_attribute) do FactoryBot::Attribute::Dynamic.new(:email, false, ->(u) { "#{u.full_name}@example.com" }) end let(:author_attribute) { FactoryBot::Attribute::Association.new(:author, :user, {}) } let(:profile_attribute) { FactoryBot::Attribute::Association.new(:profile, :profile, {}) } before do subject.define_attribute(email_attribute) subject.define_attribute(author_attribute) subject.define_attribute(profile_attribute) end it "returns associations" do expect(subject.associations.to_a).to eq [author_attribute, profile_attribute] end end describe FactoryBot::AttributeList, "filter based on ignored attributes" do 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 before do subject.define_attribute(build_ignored_attribute(:comments_count)) subject.define_attribute(build_ignored_attribute(:posts_count)) subject.define_attribute(build_non_ignored_attribute(:email)) subject.define_attribute(build_non_ignored_attribute(:first_name)) subject.define_attribute(build_non_ignored_attribute(:last_name)) end it "filters #ignored attributes" do expect(subject.ignored.map(&:name)).to eq [:comments_count, :posts_count] end it "filters #non_ignored attributes" do expect(subject.non_ignored.map(&:name)).to eq [:email, :first_name, :last_name] end end describe FactoryBot::AttributeList, "generating names" do 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 before do subject.define_attribute(build_ignored_attribute(:comments_count)) subject.define_attribute(build_ignored_attribute(:posts_count)) subject.define_attribute(build_non_ignored_attribute(:email)) subject.define_attribute(build_non_ignored_attribute(:first_name)) subject.define_attribute(build_non_ignored_attribute(:last_name)) subject.define_attribute(build_association(:avatar)) end it "knows all its #names" do expect(subject.names).to eq [:comments_count, :posts_count, :email, :first_name, :last_name, :avatar] end it "knows all its #names for #ignored attributes" do expect(subject.ignored.names).to eq [:comments_count, :posts_count] end it "knows all its #names for #non_ignored attributes" do expect(subject.non_ignored.names).to eq [:email, :first_name, :last_name, :avatar] end it "knows all its #names for #associations" do expect(subject.associations.names).to eq [:avatar] end end factory_bot-5.1.1/spec/factory_bot/attribute_spec.rb000066400000000000000000000003031354522733100226410ustar00rootroot00000000000000describe FactoryBot::Attribute do let(:name) { "user" } subject { FactoryBot::Attribute.new(name, false) } its(:name) { should eq name.to_sym } it { should_not be_association } end factory_bot-5.1.1/spec/factory_bot/callback_spec.rb000066400000000000000000000024521354522733100224010ustar00rootroot00000000000000describe 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 it "allows valid callback names to be assigned" do FactoryBot::Internal.callback_names.each do |callback_name| expect { FactoryBot::Callback.new(callback_name, -> {}) }. to_not raise_error end end it "raises if an invalid callback name is assigned" do expect { FactoryBot::Callback.new(:magic_fairies, -> {}) }. to raise_error(FactoryBot::InvalidCallbackNameError, /magic_fairies is not a valid callback name/) end end factory_bot-5.1.1/spec/factory_bot/declaration/000077500000000000000000000000001354522733100215705ustar00rootroot00000000000000factory_bot-5.1.1/spec/factory_bot/declaration/association_spec.rb000066400000000000000000000022661354522733100254510ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/declaration/dynamic_spec.rb000066400000000000000000000030461354522733100245560ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/declaration/implicit_spec.rb000066400000000000000000000054501354522733100247450ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/declaration_list_spec.rb000066400000000000000000000046121354522733100241650ustar00rootroot00000000000000describe FactoryBot::DeclarationList, "#attributes" do let(:attribute_1) { double("attribute 1") } let(:attribute_2) { double("attribute 2") } let(:attribute_3) { double("attribute 3") } let(:declaration_1) do double( "declaration 1", to_attributes: [attribute_1, attribute_2], ) end let(:declaration_2) do double("declaration_2", to_attributes: [attribute_3]) end it "returns an AttributeList" do expect(subject.attributes).to be_a(FactoryBot::AttributeList) end let(:attribute_list) { double("attribute list", define_attribute: true) } it "defines each attribute on the attribute list" do allow(FactoryBot::AttributeList).to receive(:new).and_return attribute_list subject.declare_attribute(declaration_1) subject.declare_attribute(declaration_2) subject.attributes expect(attribute_list).to have_received(:define_attribute).with(attribute_1) expect(attribute_list).to have_received(:define_attribute).with(attribute_2) expect(attribute_list).to have_received(:define_attribute).with(attribute_3) end end describe FactoryBot::DeclarationList, "#declare_attribute" do let(:declaration_1) { double("declaration", name: "declaration 1") } let(:declaration_2) { double("declaration", name: "declaration 2") } let(:declaration_with_same_name) do double("declaration", name: "declaration 1") end context "when not overridable" do it "adds the declaration to the list" do subject.declare_attribute(declaration_1) expect(subject.to_a).to eq [declaration_1] subject.declare_attribute(declaration_2) expect(subject.to_a).to eq [declaration_1, declaration_2] end end context "when overridable" do before { subject.overridable } it "adds the declaration to the list" do subject.declare_attribute(declaration_1) expect(subject.to_a).to eq [declaration_1] subject.declare_attribute(declaration_2) expect(subject.to_a).to eq [declaration_1, declaration_2] end it "deletes declarations with the same name" do subject.declare_attribute(declaration_1) expect(subject.to_a).to eq [declaration_1] subject.declare_attribute(declaration_2) expect(subject.to_a).to eq [declaration_1, declaration_2] subject.declare_attribute(declaration_with_same_name) expect(subject.to_a).to eq [declaration_2, declaration_with_same_name] end end end factory_bot-5.1.1/spec/factory_bot/decorator/000077500000000000000000000000001354522733100212655ustar00rootroot00000000000000factory_bot-5.1.1/spec/factory_bot/decorator/attribute_hash_spec.rb000066400000000000000000000013221354522733100256300ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/definition_proxy_spec.rb000066400000000000000000000176741354522733100242520ustar00rootroot00000000000000describe FactoryBot::DefinitionProxy, "#add_attribute" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "declares a dynamic attribute on the factory" do attribute_value = -> { "dynamic attribute" } proxy.add_attribute(:attribute_name, &attribute_value) expect(subject).to have_dynamic_declaration(:attribute_name). with_value(attribute_value) end end describe FactoryBot::DefinitionProxy, "#add_attribute when the proxy ignores attributes" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject, true) } it "declares a dynamic attribute on the factory" do attribute_value = -> { "dynamic attribute" } proxy.add_attribute(:attribute_name, &attribute_value) expect(subject).to have_dynamic_declaration(:attribute_name). ignored. with_value(attribute_value) end end describe FactoryBot::DefinitionProxy, "#transient" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "makes all attributes added ignored" do attribute_value = -> { "dynamic_attribute" } proxy.transient do add_attribute(:attribute_name, &attribute_value) end expect(subject).to have_dynamic_declaration(:attribute_name). ignored. with_value(attribute_value) end end describe FactoryBot::DefinitionProxy, "#method_missing" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } context "when called without args or a block" do it "declares an implicit declaration" do proxy.bogus expect(subject).to have_implicit_declaration(:bogus).with_factory(subject) end end context "when called with a ':factory' key" do it "declares an association" do proxy.author factory: :user expect(subject).to have_association_declaration(:author). with_options(factory: :user) end end context "when called with a block" do it "declares a dynamic attribute" do attribute_value = -> { "dynamic attribute" } proxy.attribute_name(&attribute_value) expect(subject).to have_dynamic_declaration(:attribute_name). with_value(attribute_value) end end context "when called with a static-attribute-like argument" do it "raises a NoMethodError" 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 end describe FactoryBot::DefinitionProxy, "#sequence" do before do allow(FactoryBot::Sequence).to receive(:new).and_call_original end 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 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 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 sequence_block = Proc.new { |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 context "when passing a block" do it "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 end describe FactoryBot::DefinitionProxy, "adding callbacks" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } let(:callback) { -> { "my awesome callback!" } } context "#after(:build)" do before { proxy.after(:build, &callback) } it { should have_callback(:after_build).with_block(callback) } end context "#after(:create)" do before { proxy.after(:create, &callback) } it { should have_callback(:after_create).with_block(callback) } end context "#after(:stub)" do before { proxy.after(:stub, &callback) } it { should have_callback(:after_stub).with_block(callback) } end context "#after(:stub, :create)" do before { proxy.after(:stub, :create, &callback) } it { should have_callback(:after_stub).with_block(callback) } it { should have_callback(:after_create).with_block(callback) } end context "#before(:stub, :create)" do before { proxy.before(:stub, :create, &callback) } it { should have_callback(:before_stub).with_block(callback) } it { should have_callback(:before_create).with_block(callback) } end context "#callback(:after_stub, :before_create)" do before { proxy.callback(:after_stub, :before_create, &callback) } it { should have_callback(:after_stub).with_block(callback) } it { should have_callback(:before_create).with_block(callback) } end end describe FactoryBot::DefinitionProxy, "#to_create" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "accepts a block to run in place of #save!" do to_create_block = ->(record) { record.persist } proxy.to_create(&to_create_block) expect(subject.to_create).to eq to_create_block end end describe FactoryBot::DefinitionProxy, "#factory" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "without options" do proxy.factory(:child) expect(proxy.child_factories).to include([:child, {}, nil]) end it "with options" do proxy.factory(:child, awesome: true) expect(proxy.child_factories).to include([:child, { awesome: true }, nil]) end it "with a block" do child_block = -> {} proxy.factory(:child, {}, &child_block) expect(proxy.child_factories).to include([:child, {}, child_block]) end end describe FactoryBot::DefinitionProxy, "#trait" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "declares a trait" do male_trait = Proc.new { gender { "Male" } } proxy.trait(:male, &male_trait) expect(subject).to have_trait(:male).with_block(male_trait) end end describe FactoryBot::DefinitionProxy, "#initialize_with" do subject { FactoryBot::Definition.new(:name) } let(:proxy) { FactoryBot::DefinitionProxy.new(subject) } it "defines the constructor on the definition" do constructor = Proc.new { Array.new } proxy.initialize_with(&constructor) expect(subject.constructor).to eq constructor end end factory_bot-5.1.1/spec/factory_bot/definition_spec.rb000066400000000000000000000037321354522733100227770ustar00rootroot00000000000000describe FactoryBot::Definition do subject { described_class.new(:name) } it { should delegate(:declare_attribute).to(:declarations) } describe "with a name" do it "creates a new attribute list with the name passed" do name = "great name" allow(FactoryBot::DeclarationList).to receive(:new) FactoryBot::Definition.new(name) expect(FactoryBot::DeclarationList).to have_received(:new).with(name) end end describe "#name" do it "returns the name" do name = "factory name" definition = described_class.new(name) expect(definition.name).to eq(name) end end describe "#overridable" do let(:list) { double("declaration list", overridable: true) } before do allow(FactoryBot::DeclarationList).to receive(:new).and_return list end it "sets the declaration list as overridable" do expect(subject.overridable).to eq subject expect(list).to have_received(:overridable).once end end describe "defining traits" do let(:trait_1) { double("trait") } let(:trait_2) { double("trait") } it "maintains a list of traits" do subject.define_trait(trait_1) subject.define_trait(trait_2) expect(subject.defined_traits).to include(trait_1, trait_2) end it "adds only unique traits" do subject.define_trait(trait_1) subject.define_trait(trait_1) expect(subject.defined_traits.size).to eq 1 end end describe "adding callbacks" do let(:callback_1) { "callback1" } let(:callback_2) { "callback2" } it "maintains a list of callbacks" do subject.add_callback(callback_1) subject.add_callback(callback_2) expect(subject.callbacks).to eq [callback_1, callback_2] end end describe "#to_create" do its(:to_create) { should be_nil } it "returns the assigned value when given a block" do block = proc { nil } subject.to_create(&block) expect(subject.to_create).to eq block end end end factory_bot-5.1.1/spec/factory_bot/disallows_duplicates_registry_spec.rb000066400000000000000000000013271354522733100270130ustar00rootroot00000000000000describe FactoryBot::Decorator::DisallowsDuplicatesRegistry do let(:registry) { double("registry", name: "Great thing", register: true) } subject { described_class.new(registry) } it "delegates #register to the registry when not registered" do allow(registry).to receive(:registered?).and_return false subject.register(:awesome, {}) expect(registry).to have_received(:register).with(:awesome, {}) end it "raises when attempting to #register a previously registered strategy" do allow(registry).to receive(:registered?).and_return true expect { subject.register(:same_name, {}) }. to raise_error(FactoryBot::DuplicateDefinitionError, "Great thing already registered: same_name") end end factory_bot-5.1.1/spec/factory_bot/evaluator_class_definer_spec.rb000066400000000000000000000045341354522733100255330ustar00rootroot00000000000000describe 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 do count += 1 nil end 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-5.1.1/spec/factory_bot/factory_spec.rb000066400000000000000000000202261354522733100223130ustar00rootroot00000000000000describe FactoryBot::Factory do before do @name = :user @class = define_class("User") @factory = FactoryBot::Factory.new(@name) FactoryBot::Internal.register_factory(@factory) end it "has a factory name" do expect(@factory.name).to eq @name end it "has a build class" do expect(@factory.build_class).to eq @class end it "returns associations" do 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, {}) 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 before do @name = :name @value = "The price is right!" @hash = { @name => @value } end it "returns the overridden value in the generated attributes" do 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 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 before do 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", ) end it "uses the passed in value for the alias" do expect(@result[:test_alias]).to eq "new" end it "discards the predefined value for the attribute" do expect(@result[:test]).to be_nil end end it "guesses the build class from the factory name" do expect(@factory.build_class).to eq User end it "creates a new factory using the class of the parent" do 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 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 subject { FactoryBot::Factory.new(:author, class: Float) } its(:build_class) { should eq Float } end describe FactoryBot::Factory, "when given a class that overrides #to_s" do let(:overriding_class) { Overriding::Class } before do define_class("Overriding") define_class("Overriding::Class") do def self.to_s "Overriding" end end end subject { FactoryBot::Factory.new(:overriding_class, class: Overriding::Class) } it "sets build_class correctly" do expect(subject.build_class).to eq overriding_class end end describe FactoryBot::Factory, "when defined with a class instead of a name" do let(:factory_class) { ArgumentError } let(:name) { :argument_error } subject { FactoryBot::Factory.new(factory_class) } its(:name) { should eq name } its(:build_class) { should eq factory_class } end describe FactoryBot::Factory, "when defined with a custom class name" do subject { FactoryBot::Factory.new(:author, class: :argument_error) } its(:build_class) { should eq ArgumentError } end describe FactoryBot::Factory, "with a name ending in s" do let(:name) { :business } let(:business_class) { Business } before { define_class("Business") } subject { FactoryBot::Factory.new(name) } its(:name) { should eq name } its(:build_class) { should eq business_class } end describe FactoryBot::Factory, "with a string for a name" do let(:name) { :string } subject { FactoryBot::Factory.new(name.to_s) } its(:name) { should eq name } end describe FactoryBot::Factory, "for namespaced class" do let(:name) { :settings } let(:settings_class) { Admin::Settings } before do define_class("Admin") define_class("Admin::Settings") end context "with a namespaced class with Namespace::Class syntax" do subject { FactoryBot::Factory.new(name, class: "Admin::Settings") } it "sets build_class correctly" do expect(subject.build_class).to eq settings_class end end context "with a namespaced class with namespace/class syntax" do subject { FactoryBot::Factory.new(name, class: "admin/settings") } it "sets build_class correctly" do expect(subject.build_class).to eq settings_class end end end describe FactoryBot::Factory, "human names" do context "factory name without underscores" do subject { FactoryBot::Factory.new(:user) } its(:names) { should eq [:user] } its(:human_names) { should eq ["user"] } end context "factory name with underscores" do subject { FactoryBot::Factory.new(:happy_user) } its(:names) { should eq [:happy_user] } its(:human_names) { should eq ["happy user"] } end context "factory name with big letters" do subject { FactoryBot::Factory.new(:LoL) } its(:names) { should eq [:LoL] } its(:human_names) { should eq ["lol"] } end context "factory name with aliases" do subject { FactoryBot::Factory.new(:happy_user, aliases: [:gleeful_user, :person]) } its(:names) { should eq [:happy_user, :gleeful_user, :person] } its(:human_names) { should eq ["happy user", "gleeful user", "person"] } end end describe FactoryBot::Factory, "running a factory" do subject { FactoryBot::Factory.new(:user) } let(:attribute) do FactoryBot::Attribute::Dynamic.new(:name, false, -> { "value" }) end let(:declaration) do FactoryBot::Declaration::Dynamic.new(:name, false, -> { "value" }) end let(:strategy) { double("strategy", result: "result", add_observer: true) } let(:attributes) { [attribute] } let(:attribute_list) do double("attribute-list", declarations: [declaration], to_a: attributes) end before do 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 subject.declare_attribute(declaration) end it "creates the right strategy using the build class when running" do subject.run(FactoryBot::Strategy::Build, {}) expect(FactoryBot::Strategy::Build).to have_received(:new).once end it "returns the result from the strategy when running" do expect(subject.run(FactoryBot::Strategy::Build, {})).to eq "result" end it "calls the block and returns the result" do block_run = nil block = ->(_result) { block_run = "changed" } subject.run(FactoryBot::Strategy::Build, {}, &block) expect(block_run).to eq "changed" end end factory_bot-5.1.1/spec/factory_bot/find_definitions_spec.rb000066400000000000000000000075351354522733100241670ustar00rootroot00000000000000shared_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-5.1.1/spec/factory_bot/internal_spec.rb000066400000000000000000000120241354522733100224550ustar00rootroot00000000000000describe 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 do FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class) end.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 describe "default strategies and callbacks" do FactoryBot::Internal::DEFAULT_STRATEGIES. each do |strategy_name, strategy_class| it "registers the #{strategy_name} strategy by default" do expect(FactoryBot::Internal.strategy_by_name(strategy_name)). to eq strategy_class end end FactoryBot::Internal::DEFAULT_CALLBACKS.each do |callback_name| it "registers the #{callback_name} by default" do expect(FactoryBot::Internal.callback_names.include?(callback_name)). to be_truthy end end end end factory_bot-5.1.1/spec/factory_bot/null_factory_spec.rb000066400000000000000000000007451354522733100233510ustar00rootroot00000000000000describe FactoryBot::NullFactory do it { should delegate(:defined_traits).to(:definition) } it { should delegate(:callbacks).to(:definition) } it { should delegate(:attributes).to(:definition) } it { should delegate(:constructor).to(:definition) } its(:compile) { should be_nil } its(:class_name) { should be_nil } its(:attributes) { should be_an_instance_of(FactoryBot::AttributeList) } its(:evaluator_class) { should eq FactoryBot::Evaluator } end factory_bot-5.1.1/spec/factory_bot/null_object_spec.rb000066400000000000000000000012501354522733100231400ustar00rootroot00000000000000describe FactoryBot::NullObject do let(:methods_to_respond_to) { %w[id age name admin?] } let(:methods_to_not_respond_to) { %w[email date_of_birth title] } subject { FactoryBot::NullObject.new(methods_to_respond_to) } it "responds to the given methods" do methods_to_respond_to.each do |method_name| expect(subject.__send__(method_name)).to be_nil expect(subject).to respond_to(method_name) end end it "does not respond to other methods" do methods_to_not_respond_to.each do |method_name| expect { subject.__send__(method_name) }.to raise_error(NoMethodError) expect(subject).not_to respond_to(method_name) end end end factory_bot-5.1.1/spec/factory_bot/registry_spec.rb000066400000000000000000000037321354522733100225170ustar00rootroot00000000000000describe FactoryBot::Registry do let(:registered_object) { double("registered object") } let(:second_registered_object) { double("second registered object") } subject { FactoryBot::Registry.new("Great thing") } it { should be_kind_of(Enumerable) } it "finds a registered object" do subject.register(:object_name, registered_object) expect(subject.find(:object_name)).to eq registered_object end it "finds a registered object with square brackets" do subject.register(:object_name, registered_object) expect(subject[:object_name]).to eq registered_object end it "raises when an object cannot be found" do expect { subject.find(:object_name) }. to raise_error(KeyError, "Great thing not registered: \"object_name\"") end it "adds and returns the object registered" do expect(subject.register(:object_name, registered_object)).to eq registered_object end it "knows that an object is registered by symbol" do subject.register(:object_name, registered_object) expect(subject).to be_registered(:object_name) end it "knows that an object is registered by string" do subject.register(:object_name, registered_object) expect(subject).to be_registered("object_name") end it "knows when an object is not registered" do expect(subject).not_to be_registered("bogus") end it "iterates registered objects" do subject.register(:first_object, registered_object) subject.register(:second_object, second_registered_object) expect(subject.to_a).to eq [registered_object, second_registered_object] end it "does not include duplicate objects with registered under different names" do subject.register(:first_object, registered_object) subject.register(:second_object, registered_object) expect(subject.to_a).to eq [registered_object] end it "clears registered factories" do subject.register(:object_name, registered_object) subject.clear expect(subject.count).to be_zero end end factory_bot-5.1.1/spec/factory_bot/sequence_spec.rb000066400000000000000000000060021354522733100224500ustar00rootroot00000000000000shared_examples "a sequence" do |options| first_value = options[:first_value] second_value = options[:second_value] its(:next) { should eq first_value } context "when incrementing" do before { subject.next } its(:next) { should eq second_value } end context "after rewinding" do before do subject.next subject.rewind end its(:next) { should 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 its(:names) { should eq [:test, :alias, :other] } 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 its(:names) { should eq [:test, :alias, :other] } 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 expect(subject.next).to eq "=foo" expect(subject.next).to eq "=bar" expect { subject.next }.to raise_error(StopIteration) end it_behaves_like "a sequence", first_value: "=foo", second_value: "=bar" end describe "a custom sequence and scope" do subject { FactoryBot::Sequence.new(:name, "A") { |n| "=#{n}#{foo}" } } let(:scope) { double("scope", foo: "attribute") } it "increments within the correct scope" do expect(subject.next(scope)).to eq "=Aattribute" end context "when incrementing" do before { subject.next(scope) } it "increments within the correct scope" do expect(subject.next(scope)).to eq "=Battribute" end end context "after rewinding" do before do subject.next(scope) subject.rewind end it "increments within the correct scope" do expect(subject.next(scope)).to eq "=Aattribute" end end end end factory_bot-5.1.1/spec/factory_bot/strategy/000077500000000000000000000000001354522733100211455ustar00rootroot00000000000000factory_bot-5.1.1/spec/factory_bot/strategy/attributes_for_spec.rb000066400000000000000000000007361354522733100255460ustar00rootroot00000000000000describe 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 do subject.result(evaluation) end.to_not raise_error end end factory_bot-5.1.1/spec/factory_bot/strategy/build_spec.rb000066400000000000000000000003621354522733100236040ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/strategy/create_spec.rb000066400000000000000000000007001354522733100237440ustar00rootroot00000000000000describe 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-5.1.1/spec/factory_bot/strategy/stub_spec.rb000066400000000000000000000051551354522733100234670ustar00rootroot00000000000000shared_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") do attr_accessor :id, :created_at end.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-5.1.1/spec/factory_bot/strategy_calculator_spec.rb000066400000000000000000000013431354522733100247160ustar00rootroot00000000000000describe FactoryBot::StrategyCalculator do let(:strategy) do define_class("MyAwesomeClass") end context "when a class" do subject { FactoryBot::StrategyCalculator.new(strategy).strategy } it "returns the class passed" do expect(subject).to eq strategy end end context "when a symbol" do before do allow(FactoryBot::Internal).to receive(:strategy_by_name).and_return(strategy) end subject { FactoryBot::StrategyCalculator.new(:build).strategy } it "finds the strategy by name" do subject expect(FactoryBot::Internal).to have_received(:strategy_by_name).with(:build) end it "returns the strategy found" do expect(subject).to eq strategy end end end factory_bot-5.1.1/spec/factory_bot_spec.rb000066400000000000000000000020151354522733100206400ustar00rootroot00000000000000describe FactoryBot do let(:factory) { FactoryBot::Factory.new(:object) } let(:sequence) { FactoryBot::Sequence.new(:email) } let(:trait) { FactoryBot::Trait.new(:admin) } it "finds a registered factory", :silence_deprecation do FactoryBot.register_factory(factory) expect(FactoryBot.factory_by_name(factory.name)).to eq factory end it "finds a registered sequence", :silence_deprecation do FactoryBot.register_sequence(sequence) expect(FactoryBot.sequence_by_name(sequence.name)).to eq sequence end it "finds a registered trait", :silence_deprecation do FactoryBot.register_trait(trait) expect(FactoryBot.trait_by_name(trait.name)).to eq trait end 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-5.1.1/spec/spec_helper.rb000066400000000000000000000012141354522733100176040ustar00rootroot00000000000000require "rspec" require "rspec/its" require "simplecov" require "factory_bot" 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-5.1.1/spec/support/000077500000000000000000000000001354522733100165045ustar00rootroot00000000000000factory_bot-5.1.1/spec/support/macros/000077500000000000000000000000001354522733100177705ustar00rootroot00000000000000factory_bot-5.1.1/spec/support/macros/define_constant.rb000066400000000000000000000027741354522733100234720ustar00rootroot00000000000000require "active_record" module DefineConstantMacros def define_class(path, base = Object, &block) const = stub_const(path, Class.new(base)) const.class_eval(&block) if block_given? 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 => exception # rubocop:disable Lint/RescueException connection.execute("DROP TABLE IF EXISTS #{table_name}") raise exception 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-5.1.1/spec/support/macros/deprecation.rb000066400000000000000000000003461354522733100226150ustar00rootroot00000000000000require "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-5.1.1/spec/support/macros/temporary_assignment.rb000066400000000000000000000006271354522733100245740ustar00rootroot00000000000000module 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-5.1.1/spec/support/matchers/000077500000000000000000000000001354522733100203125ustar00rootroot00000000000000factory_bot-5.1.1/spec/support/matchers/be_about_now.rb000066400000000000000000000001761354522733100233060ustar00rootroot00000000000000RSpec::Matchers.define :be_about_now do match do |actual| expect(actual).to be_within(2.seconds).of(Time.now) end end factory_bot-5.1.1/spec/support/matchers/callback.rb000066400000000000000000000003431354522733100223730ustar00rootroot00000000000000RSpec::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-5.1.1/spec/support/matchers/declaration.rb000066400000000000000000000031351354522733100231260ustar00rootroot00000000000000module 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-5.1.1/spec/support/matchers/delegate.rb000066400000000000000000000021131354522733100224060ustar00rootroot00000000000000RSpec::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-5.1.1/spec/support/matchers/trait.rb000066400000000000000000000004041354522733100217600ustar00rootroot00000000000000RSpec::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-5.1.1/spec/support/shared_examples/000077500000000000000000000000001354522733100216505ustar00rootroot00000000000000factory_bot-5.1.1/spec/support/shared_examples/strategy.rb000066400000000000000000000060561354522733100240460ustar00rootroot00000000000000shared_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") do attr_accessor :id end.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