factory_girl-4.5.0/0000755000004100000410000000000012435642645014247 5ustar www-datawww-datafactory_girl-4.5.0/Rakefile0000644000004100000410000000156212435642645015720 0ustar www-datawww-datarequire 'rubygems' require 'bundler' require 'rake' require 'appraisal' require 'yard' require 'rspec/core/rake_task' require 'cucumber/rake/task' Bundler::GemHelper.install_tasks desc 'Default: run the specs and features.' task :default do system("bundle exec rake -s appraisal spec:unit spec:acceptance features;") end namespace :spec do desc "Run unit specs" RSpec::Core::RakeTask.new('unit') do |t| t.pattern = 'spec/{*_spec.rb,factory_girl/**/*_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_girl-4.5.0/Gemfile.lock0000644000004100000410000000414312435642645016473 0ustar www-datawww-dataPATH remote: . specs: factory_girl (4.5.0) activesupport (>= 3.0.0) GEM remote: https://rubygems.org/ specs: activemodel (4.0.0) activesupport (= 4.0.0) builder (~> 3.1.0) activerecord (4.0.0) activemodel (= 4.0.0) activerecord-deprecated_finders (~> 1.0.2) activesupport (= 4.0.0) arel (~> 4.0.0) activerecord-deprecated_finders (1.0.3) activesupport (4.0.0) i18n (~> 0.6, >= 0.6.4) minitest (~> 4.2) multi_json (~> 1.3) thread_safe (~> 0.1) tzinfo (~> 0.3.37) appraisal (1.0.0) bundler rake thor (>= 0.14.0) arel (4.0.2) aruba (0.5.3) childprocess (>= 0.3.6) cucumber (>= 1.1.1) rspec-expectations (>= 2.7.0) atomic (1.1.10) atomic (1.1.10-java) bourne (1.5.0) mocha (>= 0.13.2, < 0.15) builder (3.1.4) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.3.15) builder (>= 2.1.2) diff-lcs (>= 1.1.3) gherkin (~> 2.12) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.1) diff-lcs (1.1.3) ffi (1.9.0) ffi (1.9.0-java) gherkin (2.12.2) multi_json (~> 1.3) gherkin (2.12.2-java) multi_json (~> 1.3) i18n (0.6.4) metaclass (0.0.1) minitest (4.7.5) mocha (0.14.0) metaclass (~> 0.0.1) multi_json (1.10.1) multi_test (0.1.1) rake (10.3.2) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.2) rspec-expectations (2.12.1) diff-lcs (~> 1.1.3) rspec-mocks (2.12.2) simplecov (0.7.1) multi_json (~> 1.0) simplecov-html (~> 0.7.1) simplecov-html (0.7.1) sqlite3 (1.3.8) thor (0.19.1) thread_safe (0.1.2) atomic thread_safe (0.1.2-java) atomic timecop (0.6.2.2) tzinfo (0.3.37) yard (0.8.7) PLATFORMS java ruby DEPENDENCIES activerecord (>= 3.0.0) appraisal (~> 1.0.0) aruba bourne cucumber (~> 1.3.15) factory_girl! mocha (>= 0.12.8) rspec (~> 2.12.0) simplecov sqlite3 timecop yard factory_girl-4.5.0/Gemfile0000644000004100000410000000004712435642645015543 0ustar www-datawww-datasource 'https://rubygems.org' gemspec factory_girl-4.5.0/.autotest0000644000004100000410000000077512435642645016131 0ustar www-datawww-dataAutotest.add_hook :initialize do |at| at.clear_mappings at.add_mapping(%r{^test/.*_test\.rb$}) {|f, _| [f] } at.add_mapping(%r{^lib/factory_girl/(.*)\.rb$}) {|_, m| ["test/#{m[1]}_test.rb", "test/integration_test.rb"] } at.add_mapping(%r{^test/(test_helper|models)\.rb$}) { at.files_matching %r{^test/.*_test\.rb$} } at.add_mapping(%r{^lib/.*\.rb$}) { at.files_matching %r{^test/.*_test\.rb$} } end factory_girl-4.5.0/features/0000755000004100000410000000000012435642645016065 5ustar www-datawww-datafactory_girl-4.5.0/features/find_definitions.feature0000644000004100000410000000432012435642645022754 0ustar www-datawww-dataFeature: FactoryGirl can find factory definitions correctly Scenario: Find definitions with a path Given a file named "awesome_factories.rb" with: """ FactoryGirl.define do factory :awesome_category, :class => Category do name "awesome!!!" end end """ When "awesome_factories.rb" is added to FactoryGirl's file definitions path And I create a "awesome_category" instance from FactoryGirl 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: """ FactoryGirl.define do factory :another_awesome_category, :class => Category do name "awesome!!!" end end """ When "awesome_factories.rb" is added to FactoryGirl's file definitions path as an absolute path And I create a "another_awesome_category" instance from FactoryGirl 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: """ FactoryGirl.define do factory :great_category, :class => Category do name "great!!!" end end """ When "nested" is added to FactoryGirl's file definitions path And I create a "great_category" instance from FactoryGirl Then I should find the following for the last category: | name | | great!!! | Scenario: Reload FactoryGirl Given a file named "nested/reload_factories.rb" with: """ FactoryGirl.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 FactoryGirl's file definitions path And I append to "nested/reload_factories.rb" with: """ FactoryGirl.modify do factory :handy_category do name "HANDY!!!" end end """ And I reload factories And I create a "handy_category" instance from FactoryGirl Then I should find the following for the last category: | name | | HANDY!!! | factory_girl-4.5.0/features/step_definitions/0000755000004100000410000000000012435642645021433 5ustar www-datawww-datafactory_girl-4.5.0/features/step_definitions/database_steps.rb0000644000004100000410000000033312435642645024741 0ustar www-datawww-dataThen /^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_girl-4.5.0/features/step_definitions/factory_girl_steps.rb0000644000004100000410000000200712435642645025661 0ustar www-datawww-datamodule FactoryGirlDefinitionsHelper def append_file_to_factory_girl_definitions_path(path_to_file) FactoryGirl.definition_file_paths ||= [] FactoryGirl.definition_file_paths << path_to_file end end World(FactoryGirlDefinitionsHelper) When /^"([^"]*)" is added to FactoryGirl's file definitions path$/ do |file_name| new_factory_file = File.join(current_dir, file_name.gsub(".rb", "")) append_file_to_factory_girl_definitions_path(new_factory_file) step %{I find definitions} end When /^"([^"]*)" is added to FactoryGirl's file definitions path as an absolute path$/ do |file_name| new_factory_file = File.expand_path(File.join(current_dir, file_name.gsub(".rb", ""))) append_file_to_factory_girl_definitions_path(new_factory_file) step %{I find definitions} end When /^I create a "([^"]*)" instance from FactoryGirl$/ do |factory_name| FactoryGirl.create(factory_name) end When /^I find definitions$/ do FactoryGirl.find_definitions end When /^I reload factories$/ do FactoryGirl.reload end factory_girl-4.5.0/features/support/0000755000004100000410000000000012435642645017601 5ustar www-datawww-datafactory_girl-4.5.0/features/support/factories.rb0000644000004100000410000000060012435642645022101 0ustar www-datawww-dataActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => File.join(File.dirname(__FILE__), 'test.db') ) class CreateSchema < ActiveRecord::Migration 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_girl-4.5.0/features/support/env.rb0000644000004100000410000000032412435642645020715 0ustar www-datawww-dataPROJECT_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) require "simplecov" $: << File.join(PROJECT_ROOT, 'lib') require 'active_record' require 'factory_girl' require 'aruba/cucumber' factory_girl-4.5.0/.rspec0000644000004100000410000000003212435642645015357 0ustar www-datawww-data--format progress --color factory_girl-4.5.0/GETTING_STARTED.md0000644000004100000410000007237712435642645017100 0ustar www-datawww-dataGetting Started =============== Update Your Gemfile ------------------- If you're using Rails, you'll need to change the required version of `factory_girl_rails`: ```ruby gem "factory_girl_rails", "~> 4.0" ``` If you're *not* using Rails, you'll just have to change the required version of `factory_girl`: ```ruby gem "factory_girl", "~> 4.0" ``` JRuby users: factory_girl 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 ------------------------- ```ruby # RSpec # spec/support/factory_girl.rb RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end # Test::Unit class Test::Unit::TestCase include FactoryGirl::Syntax::Methods end # Cucumber World(FactoryGirl::Syntax::Methods) # Spinach class Spinach::FeatureSteps include FactoryGirl::Syntax::Methods end # MiniTest class MiniTest::Unit::TestCase include FactoryGirl::Syntax::Methods end # MiniTest::Spec class MiniTest::Spec include FactoryGirl::Syntax::Methods end # minitest-rails class MiniTest::Rails::ActiveSupport::TestCase include FactoryGirl::Syntax::Methods end ``` If you do not include `FactoryGirl::Syntax::Methods` in your test suite, then all factory_girl methods will need to be prefaced with `FactoryGirl`. Linting Factories ----------------- factory_girl allows for linting known factories: ```ruby FactoryGirl.lint ``` `FactoryGirl.lint` builds each factory and subsequently calls `#valid?` on it (if `#valid?` is defined); if any calls to `#valid?` return `false`, `FactoryGirl::InvalidFactoryError` is raised with a list of the offending factories. Recommended usage of `FactoryGirl.lint` is to invoke this once before the test suite is run. With RSpec: ```ruby # spec/support/factory_girl.rb RSpec.configure do |config| # additional factory_girl configuration config.before(:suite) do begin DatabaseCleaner.start FactoryGirl.lint ensure DatabaseCleaner.clean end end end ``` After calling `FactoryGirl.lint`, you'll likely want to clear out the database, as built factories will create associated records. The provided example above uses the database_cleaner gem to clear out the database; be sure to add the gem to your Gemfile under the appropriate groups. You can lint factories selectively by passing only factories you want linted: ```ruby factories_to_lint = FactoryGirl.factories.reject do |factory| factory.name =~ /^old_/ end FactoryGirl.lint factories_to_lint ``` This would lint all factories that aren't prefixed with `old_`. 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, but it's possible to explicitly specify it: ```ruby # This will guess the User class FactoryGirl.define do factory :user do first_name "John" last_name "Doe" admin false end # This will use the User class (Admin would have been guessed) factory :admin, class: User do first_name "Admin" last_name "User" admin true end 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 if they are defined in files at the following locations: test/factories.rb spec/factories.rb test/factories/*.rb spec/factories/*.rb Using factories --------------- factory\_girl 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" ``` Lazy Attributes --------------- Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as associations and other attributes that must be dynamically generated) will need values assigned each time an instance is generated. These "lazy" attributes can be added by passing a block instead of a parameter: ```ruby factory :user do # ... activation_code { User.generate_activation_code } date_of_birth { 21.years.ago } end ``` Aliases ------- Aliases allow you to use named associations more easily. ```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 lazy 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" ``` Static and dynamic attributes can be created as transient attributes. 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_girl's dynamic attributes, you can access transient attributes as you would expect. If you need to access the evaluator in a factory_girl callback, you'll need to declare a second block argument (for the evaluator) and access transient attributes from there. 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 ``` The behavior of the association method varies depending on the build strategy used for the parent object. ```ruby # 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 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 FactoryGirl.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 ``` 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. 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 FactoryGirl.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 as attributes: ```ruby factory :user do email end ``` Or in lazy attributes: ```ruby factory :invite do invitee { generate(:email) } end ``` 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. 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 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 ``` 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_girl. ```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 ``` Finally, traits can be used within other traits to mix in their attributes. ```ruby FactoryGirl.define do factory :order do trait :completed do completed_at { 3.days.ago } end trait :refunded do completed refunded_at { 1.day.ago } end end end ``` Callbacks --------- factory\_girl makes available four callbacks for injecting some code: * after(:build) - called after a factory is built (via `FactoryGirl.build`, `FactoryGirl.create`) * before(:create) - called before a factory is saved (via `FactoryGirl.create`) * after(:create) - called after a factory is saved (via `FactoryGirl.create`) * after(:stub) - called after a factory is stubbed (via `FactoryGirl.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 `FactoryGirl.define` block: ```ruby FactoryGirl.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 FactoryGirl.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 FactoryGirl.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 FactoryGirl.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 FactoryGirl.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). `FactoryGirl.modify` must be called outside of a `FactoryGirl.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) ``` 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 ``` Custom Construction ------------------- If you want to use factory_girl 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_girl 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, evalued sequences, etc.) You can define `initialize_with` for all factories by including it in the `FactoryGirl.define` block: ```ruby FactoryGirl.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 FactoryGirl.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_girl before 4.0, it would run this: ```ruby FactoryGirl.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\_girl by adding a custom build strategy. Strategies define two methods: `association` and `result`. `association` receives a `FactoryGirl::FactoryRunner` instance, upon which you can call `run`, overriding the strategy if you want. The second method, `result`, receives a `FactoryGirl::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\_girl 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 `FactoryGirl::Strategy::Create` to build a JSON representation of your model. ```ruby class JsonStrategy def initialize @strategy = FactoryGirl.strategy_by_name(:create).new end delegate :association, to: :@strategy def result(evaluation) @strategy.result(evaluation).to_json end end ``` For factory\_girl to recognize the new strategy, you can register it: ```ruby FactoryGirl.register_strategy(:json, JsonStrategy) ``` This allows you to call ```ruby FactoryGirl.json(:user) ``` Finally, you can override factory\_girl'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 = FactoryGirl.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 FactoryGirl.register_strategy(:json, JsonStrategy) FactoryGirl.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 `FactoryGirl.define` block: ```ruby FactoryGirl.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_girl.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_girl_results = {} config.before(:suite) do ActiveSupport::Notifications.subscribe("factory_girl.run_factory") do |name, start, finish, id, payload| factory_name = payload[:name] strategy_name = payload[:strategy] factory_girl_results[factory_name] ||= {} factory_girl_results[factory_name][strategy_name] ||= 0 factory_girl_results[factory_name][strategy_name] += 1 end end config.after(:suite) do puts factory_girl_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 FactoryGirl.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 `FactoryGirl.reload` to the RSpec configuration, like so: ```ruby RSpec.configure do |config| config.before(:suite) { FactoryGirl.reload } end ``` Using Without Bundler --------------------- If you're not using Bundler, be sure to have the gem installed and call: ```ruby require 'factory_girl' ``` Once required, assuming you have a directory structure of `spec/factories` or `test/factories`, all you'll need to do is run ```ruby FactoryGirl.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 FactoryGirl.definition_file_paths = %w(custom_factories_directory) FactoryGirl.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_girl' FactoryGirl.define do factory :user do name 'John Doe' date_of_birth { 21.years.ago } end end ``` factory_girl-4.5.0/NEWS0000644000004100000410000002631412435642645014754 0ustar www-datawww-data4.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_girl'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 trialing 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_girl.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_girl-4.5.0/factory_girl.gemspec0000644000004100000410000000326412435642645020305 0ustar www-datawww-data$LOAD_PATH << File.expand_path("../lib", __FILE__) require 'factory_girl/version' Gem::Specification.new do |s| s.name = %q{factory_girl} s.version = FactoryGirl::VERSION s.summary = %q{factory_girl provides a framework and DSL for defining and using model instance factories.} s.description = %q{factory_girl 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 = `git ls-files`.split("\n") s.test_files = `git ls-files -- Appraisals {spec,features,gemfiles}/*`.split("\n") s.require_paths = ['lib'] s.required_ruby_version = Gem::Requirement.new(">= 1.9.2") s.authors = ["Josh Clayton", "Joe Ferris"] s.email = ["jclayton@thoughtbot.com", "jferris@thoughtbot.com"] s.homepage = "https://github.com/thoughtbot/factory_girl" s.add_dependency("activesupport", ">= 3.0.0") s.add_development_dependency("rspec", "~> 2.12.0") s.add_development_dependency("cucumber", "~> 1.3.15") s.add_development_dependency("timecop") s.add_development_dependency("simplecov") s.add_development_dependency("aruba") s.add_development_dependency("mocha", ">= 0.12.8") s.add_development_dependency("bourne") s.add_development_dependency("appraisal", "~> 1.0.0") s.add_development_dependency("activerecord", ">= 3.0.0") if RUBY_PLATFORM == "java" s.add_development_dependency("activerecord-jdbcsqlite3-adapter") s.add_development_dependency("jdbc-sqlite3") else s.add_development_dependency("sqlite3") end s.add_development_dependency("yard") s.license = "MIT" end factory_girl-4.5.0/spec/0000755000004100000410000000000012435642645015201 5ustar www-datawww-datafactory_girl-4.5.0/spec/spec_helper.rb0000644000004100000410000000077612435642645020031 0ustar www-datawww-data$LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'lib') $LOAD_PATH << File.join(File.dirname(__FILE__)) require 'rubygems' require 'rspec' require 'rspec/autorun' require "simplecov" require 'factory_girl' require "mocha/api" require "bourne" require "timecop" Dir["spec/support/**/*.rb"].each { |f| require File.expand_path(f) } RSpec.configure do |config| config.mock_framework = :mocha config.include DeclarationMatchers config.after do Timecop.return FactoryGirl.reload end end factory_girl-4.5.0/spec/factory_girl/0000755000004100000410000000000012435642645017665 5ustar www-datawww-datafactory_girl-4.5.0/spec/factory_girl/declaration/0000755000004100000410000000000012435642645022152 5ustar www-datawww-datafactory_girl-4.5.0/spec/factory_girl/declaration/implicit_spec.rb0000644000004100000410000000120012435642645025314 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Declaration::Implicit do let(:name) { :author } let(:declaration) { FactoryGirl::Declaration::Implicit.new(name) } subject { declaration.to_attributes.first } context "with a known factory" do before do FactoryGirl.factories.stubs(:registered? => true) end it { should be_association } its(:factory) { should eq name } end context "with a known sequence" do before do FactoryGirl.sequences.stubs(:registered? => true) end it { should_not be_association } it { should be_a(FactoryGirl::Attribute::Sequence) } end end factory_girl-4.5.0/spec/factory_girl/null_factory_spec.rb0000644000004100000410000000077712435642645023740 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::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(FactoryGirl::AttributeList) } its(:evaluator_class) { should eq FactoryGirl::Evaluator } end factory_girl-4.5.0/spec/factory_girl/attribute_list_spec.rb0000644000004100000410000001334712435642645024272 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::AttributeList, "#define_attribute" do let(:static_attribute) { FactoryGirl::Attribute::Static.new(:full_name, "value", false) } let(:dynamic_attribute) { FactoryGirl::Attribute::Dynamic.new(:email, false, ->(u) { "#{u.full_name}@example.com" }) } it "maintains a list of attributes" do subject.define_attribute(static_attribute) expect(subject.to_a).to eq [static_attribute] subject.define_attribute(dynamic_attribute) expect(subject.to_a).to eq [static_attribute, dynamic_attribute] end it "returns the attribute" do expect(subject.define_attribute(static_attribute)).to eq static_attribute expect(subject.define_attribute(dynamic_attribute)).to eq dynamic_attribute end it "raises if an attribute has already been defined" do expect { 2.times { subject.define_attribute(static_attribute) } }.to raise_error(FactoryGirl::AttributeDefinitionError, "Attribute already defined: full_name") end end describe FactoryGirl::AttributeList, "#define_attribute with a named attribute list" do subject { FactoryGirl::AttributeList.new(:author) } let(:association_with_same_name) { FactoryGirl::Attribute::Association.new(:author, :author, {}) } let(:association_with_different_name) { FactoryGirl::Attribute::Association.new(:author, :post, {}) } it "raises when the attribute is a self-referencing association" do expect { subject.define_attribute(association_with_same_name) }.to raise_error(FactoryGirl::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 FactoryGirl::AttributeList, "#apply_attributes" do let(:full_name_attribute) { FactoryGirl::Attribute::Static.new(:full_name, "John Adams", false) } let(:city_attribute) { FactoryGirl::Attribute::Static.new(:city, "Boston", false) } let(:email_attribute) { FactoryGirl::Attribute::Dynamic.new(:email, false, ->(model) { "#{model.full_name}@example.com" }) } let(:login_attribute) { FactoryGirl::Attribute::Dynamic.new(:login, false, ->(model) { "username-#{model.full_name}" }) } def list(*attributes) FactoryGirl::AttributeList.new.tap do |list| attributes.each { |attribute| list.define_attribute(attribute) } end end it "adds attributes in the order defined regardless of attribute type" do subject.define_attribute(full_name_attribute) subject.define_attribute(login_attribute) subject.apply_attributes(list(city_attribute, email_attribute)) expect(subject.to_a).to eq [full_name_attribute, login_attribute, city_attribute, email_attribute] end end describe FactoryGirl::AttributeList, "#associations" do let(:full_name_attribute) { FactoryGirl::Attribute::Static.new(:full_name, "value", false) } let(:email_attribute) { FactoryGirl::Attribute::Dynamic.new(:email, false, ->(u) { "#{u.full_name}@example.com" }) } let(:author_attribute) { FactoryGirl::Attribute::Association.new(:author, :user, {}) } let(:profile_attribute) { FactoryGirl::Attribute::Association.new(:profile, :profile, {}) } before do subject.define_attribute(full_name_attribute) 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 FactoryGirl::AttributeList, "filter based on ignored attributes" do def build_ignored_attribute(name) FactoryGirl::Attribute::Static.new(name, "value", true) end def build_non_ignored_attribute(name) FactoryGirl::Attribute::Static.new(name, "value", false) 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 FactoryGirl::AttributeList, "generating names" do def build_ignored_attribute(name) FactoryGirl::Attribute::Static.new(name, "value", true) end def build_non_ignored_attribute(name) FactoryGirl::Attribute::Static.new(name, "value", false) end def build_association(name) FactoryGirl::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_girl-4.5.0/spec/factory_girl/factory_spec.rb0000644000004100000410000002132312435642645022674 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Factory do before do @name = :user @class = define_class('User') @factory = FactoryGirl::Factory.new(@name) FactoryGirl.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 "passes a custom creation block" do strategy = stub("strategy", result: nil, add_observer: true) FactoryGirl::Strategy::Build.stubs(new: strategy) block = -> {} factory = FactoryGirl::Factory.new(:object) factory.to_create(&block) factory.run(FactoryGirl::Strategy::Build, {}) expect(strategy).to have_received(:result).with(instance_of(FactoryGirl::Evaluation)) end it "returns associations" do factory = FactoryGirl::Factory.new(:post) FactoryGirl.register_factory(FactoryGirl::Factory.new(:admin)) factory.declare_attribute(FactoryGirl::Declaration::Association.new(:author, {})) factory.declare_attribute(FactoryGirl::Declaration::Association.new(:editor, {})) factory.declare_attribute(FactoryGirl::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 = FactoryGirl::Declaration::Association.new(:association_on_parent, {}) association_on_child = FactoryGirl::Declaration::Association.new(:association_on_child, {}) factory = FactoryGirl::Factory.new(:post) factory.declare_attribute(association_on_parent) FactoryGirl.register_factory(factory) child_factory = FactoryGirl::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 = FactoryGirl::Declaration::Static.new(@name, 'The price is wrong, Bob!') @factory.declare_attribute(declaration) result = @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) expect(result[@name]).to eq @value end it "does not call a lazy attribute block for an overridden attribute" do declaration = FactoryGirl::Declaration::Dynamic.new(@name, false, -> { flunk }) @factory.declare_attribute(declaration) @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) end it "overrides a symbol parameter with a string parameter" do declaration = FactoryGirl::Declaration::Static.new(@name, 'The price is wrong, Bob!') @factory.declare_attribute(declaration) @hash = { @name.to_s => @value } result = @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) expect(result[@name]).to eq @value end end describe "overriding an attribute with an alias" do before do @factory.declare_attribute(FactoryGirl::Declaration::Static.new(:test, 'original')) FactoryGirl.aliases << [/(.*)_alias/, '\1'] @result = @factory.run(FactoryGirl::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 = FactoryGirl::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 = FactoryGirl::Factory.new(:child, class: String, parent: @factory.name) child.compile expect(child.build_class).to eq String end end describe FactoryGirl::Factory, "when defined with a custom class" do subject { FactoryGirl::Factory.new(:author, class: Float) } its(:build_class) { should eq Float } end describe FactoryGirl::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 { FactoryGirl::Factory.new(:overriding_class, class: Overriding::Class) } it "sets build_class correctly" do expect(subject.build_class).to eq overriding_class end end describe FactoryGirl::Factory, "when defined with a class instead of a name" do let(:factory_class) { ArgumentError } let(:name) { :argument_error } subject { FactoryGirl::Factory.new(factory_class) } its(:name) { should eq name } its(:build_class) { should eq factory_class } end describe FactoryGirl::Factory, "when defined with a custom class name" do subject { FactoryGirl::Factory.new(:author, class: :argument_error) } its(:build_class) { should eq ArgumentError } end describe FactoryGirl::Factory, "with a name ending in s" do let(:name) { :business } let(:business_class) { Business } before { define_class('Business') } subject { FactoryGirl::Factory.new(name) } its(:name) { should eq name } its(:build_class) { should eq business_class } end describe FactoryGirl::Factory, "with a string for a name" do let(:name) { :string } subject { FactoryGirl::Factory.new(name.to_s) } its(:name) { should eq name } end describe FactoryGirl::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 { FactoryGirl::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 { FactoryGirl::Factory.new(name, class: "admin/settings") } it "sets build_class correctly" do expect(subject.build_class).to eq settings_class end end end describe FactoryGirl::Factory, "human names" do context "factory name without underscores" do subject { FactoryGirl::Factory.new(:user) } its(:names) { should eq [:user] } its(:human_names) { should eq ["user"] } end context "factory name with underscores" do subject { FactoryGirl::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 { FactoryGirl::Factory.new(:LoL) } its(:names) { should eq [:LoL] } its(:human_names) { should eq ["lol"] } end context "factory name with aliases" do subject { FactoryGirl::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 FactoryGirl::Factory, "running a factory" do subject { FactoryGirl::Factory.new(:user) } let(:attribute) { FactoryGirl::Attribute::Static.new(:name, "value", false) } let(:declaration) { FactoryGirl::Declaration::Static.new(:name, "value", false) } let(:strategy) { stub("strategy", result: "result", add_observer: true) } let(:attributes) { [attribute] } let(:attribute_list) { stub('attribute-list', declarations: [declaration], to_a: attributes) } before do define_model("User", name: :string) FactoryGirl::Declaration::Static.stubs(new: declaration) declaration.stubs(to_attributes: attributes) FactoryGirl::Strategy::Build.stubs(new: strategy) subject.declare_attribute(declaration) end it "creates the right strategy using the build class when running" do subject.run(FactoryGirl::Strategy::Build, {}) expect(FactoryGirl::Strategy::Build).to have_received(:new).once end it "returns the result from the strategy when running" do expect(subject.run(FactoryGirl::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(FactoryGirl::Strategy::Build, { }, &block) expect(block_run).to eq "changed" end end factory_girl-4.5.0/spec/factory_girl/strategy/0000755000004100000410000000000012435642645021527 5ustar www-datawww-datafactory_girl-4.5.0/spec/factory_girl/strategy/create_spec.rb0000644000004100000410000000117312435642645024333 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::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_class = Class.new do def initialize @block_run = false end attr_reader :block_run def create(*instance) @block_run = true end end evaluation = evaluation_class.new evaluation.stubs(object: nil, notify: nil) subject.result(evaluation) expect(evaluation.block_run).to be_true end end factory_girl-4.5.0/spec/factory_girl/strategy/build_spec.rb0000644000004100000410000000041212435642645024162 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::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_girl-4.5.0/spec/factory_girl/strategy/attributes_for_spec.rb0000644000004100000410000000076412435642645026131 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Strategy::AttributesFor do let(:result) { { name: "John Doe", gender: "Male", admin: false } } let(:evaluation) { stub("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_girl-4.5.0/spec/factory_girl/strategy/stub_spec.rb0000644000004100000410000000254612435642645024052 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::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 before { Timecop.freeze(Time.now) } let(:result_instance) do define_class("ResultInstance") do attr_accessor :id end.new end let(:evaluation) { stub("evaluation", object: result_instance, notify: true) } it { expect(subject.result(evaluation)).not_to be_new_record } it { expect(subject.result(evaluation)).to be_persisted } it "assigns created_at" do created_at = subject.result(evaluation).created_at expect(created_at).to eq Time.now Timecop.travel(150000) expect(subject.result(evaluation).created_at).to eq created_at end [:save, :destroy, :connection, :reload, :update_attribute, :update_column].each do |database_method| it "raises when attempting to connect to the database by calling #{database_method}" do expect do subject.result(evaluation).send(database_method) end.to raise_error(RuntimeError, "stubbed models are not allowed to access the database - #{subject.result(evaluation).class}##{database_method}()") end end end end factory_girl-4.5.0/spec/factory_girl/null_object_spec.rb0000644000004100000410000000130112435642645023517 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::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 { FactoryGirl::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_girl-4.5.0/spec/factory_girl/attribute_spec.rb0000644000004100000410000000100012435642645023216 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Attribute do let(:name) { "user" } subject { FactoryGirl::Attribute.new(name, false) } its(:name) { should eq name.to_sym } it { should_not be_association } it "raises an error when defining an attribute writer" do error_message = %{factory_girl uses 'test value' syntax rather than 'test = value'} expect { FactoryGirl::Attribute.new('test=', false) }.to raise_error(FactoryGirl::AttributeDefinitionError, error_message) end end factory_girl-4.5.0/spec/factory_girl/attribute/0000755000004100000410000000000012435642645021670 5ustar www-datawww-datafactory_girl-4.5.0/spec/factory_girl/attribute/dynamic_spec.rb0000644000004100000410000000275512435642645024664 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Attribute::Dynamic do let(:name) { :first_name } let(:block) { -> { } } subject { FactoryGirl::Attribute::Dynamic.new(name, false, block) } its(:name) { should eq name } context "with a block returning a static value" do let(:block) { -> { "value" } } it "returns the value when executing the proc" do expect(subject.to_proc.call).to eq "value" end end context "with a block returning its block-level variable" do let(:block) { ->(thing) { thing } } it "returns self when executing the proc" do expect(subject.to_proc.call).to eq subject end end context "with a block referencing an attribute on the attribute" do let(:block) { -> { attribute_defined_on_attribute } } let(:result) { "other attribute value" } before do subject.stubs(attribute_defined_on_attribute: 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) { -> { FactoryGirl.register_sequence(FactoryGirl::Sequence.new(:email, 1) { |n| "foo#{n}" }) } } it "raises a sequence abuse error" do expect { subject.to_proc.call }.to raise_error(FactoryGirl::SequenceAbuseError) end end end describe FactoryGirl::Attribute::Dynamic, "with a string name" do subject { FactoryGirl::Attribute::Dynamic.new("name", false, -> { } ) } its(:name) { should eq :name } end factory_girl-4.5.0/spec/factory_girl/attribute/association_spec.rb0000644000004100000410000000157712435642645025555 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Attribute::Association do let(:name) { :author } let(:factory) { :user } let(:overrides) { { first_name: "John" } } let(:association) { stub("association") } subject { FactoryGirl::Attribute::Association.new(name, factory, overrides) } before { subject.stubs(association: association) } 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 FactoryGirl::Attribute::Association, "with a string name" do subject { FactoryGirl::Attribute::Association.new("name", :user, {}) } its(:name) { should eq :name } end factory_girl-4.5.0/spec/factory_girl/attribute/static_spec.rb0000644000004100000410000000077312435642645024525 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Attribute::Static do let(:name) { :first_name } let(:value) { "John" } subject { FactoryGirl::Attribute::Static.new(name, value, false) } its(:name) { should eq name } it "returns the value when executing the proc" do expect(subject.to_proc.call).to eq value end end describe FactoryGirl::Attribute::Static, "with a string name" do subject { FactoryGirl::Attribute::Static.new("name", nil, false) } its(:name) { should eq :name } end factory_girl-4.5.0/spec/factory_girl/attribute/sequence_spec.rb0000644000004100000410000000076712435642645025051 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Attribute::Sequence do let(:sequence_name) { :name } let(:name) { :first_name } let(:sequence) { FactoryGirl::Sequence.new(sequence_name, 5) { |n| "Name #{n}" } } subject { FactoryGirl::Attribute::Sequence.new(name, sequence_name, false) } before { FactoryGirl.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_girl-4.5.0/spec/factory_girl/strategy_calculator_spec.rb0000644000004100000410000000131712435642645025301 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::StrategyCalculator do let(:strategy) do define_class("MyAwesomeClass") end context "when a class" do subject { FactoryGirl::StrategyCalculator.new(strategy).strategy } it "returns the class passed" do expect(subject).to eq strategy end end context "when a symbol" do before { FactoryGirl.stubs(:strategy_by_name).returns(strategy) } subject { FactoryGirl::StrategyCalculator.new(:build).strategy } it "finds the strategy by name" do subject expect(FactoryGirl).to have_received(:strategy_by_name).with(:build) end it "returns the strategy found" do expect(subject).to eq strategy end end end factory_girl-4.5.0/spec/factory_girl/sequence_spec.rb0000644000004100000410000000523312435642645023037 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Sequence do describe "a basic sequence" do let(:name) { :test } subject { FactoryGirl::Sequence.new(name) { |n| "=#{n}" } } its(:name) { should eq name } its(:names) { should eq [name] } its(:next) { should eq "=1" } describe "when incrementing" do before { subject.next } its(:next) { should eq "=2" } end end describe "a custom sequence" do subject { FactoryGirl::Sequence.new(:name, "A") { |n| "=#{n}" } } its(:next) { should eq "=A" } describe "when incrementing" do before { subject.next } its(:next) { should eq "=B" } end end describe "a sequence with aliases using default value" do subject { FactoryGirl::Sequence.new(:test, aliases: [:alias, :other]) { |n| "=#{n}" } } its(:next) { should eq "=1" } its(:names) { should eq [:test, :alias, :other] } describe "when incrementing" do before { subject.next } its(:next) { should eq "=2" } end end describe "a sequence with custom value and aliases" do subject { FactoryGirl::Sequence.new(:test, 3, aliases: [:alias, :other]) { |n| "=#{n}" } } its(:next) { should eq "=3" } describe "when incrementing" do before { subject.next } its(:next) { should eq "=4" } end end describe "a basic sequence without a block" do subject { FactoryGirl::Sequence.new(:name) } its(:next) { should eq 1 } describe "when incrementing" do before { subject.next } its(:next) { should eq 2 } end end describe "a custom sequence without a block" do subject { FactoryGirl::Sequence.new(:name, "A") } its(:next) { should eq "A" } describe "when incrementing" do before { subject.next } its(:next) { should eq "B" } end end describe "iterating over items in an enumerator" do subject { FactoryGirl::Sequence.new(:name, %w[foo bar].to_enum) { |n| "=#{n}" } } 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 end describe "a custom sequence and scope" do subject { FactoryGirl::Sequence.new(:name, 'A') { |n| "=#{n}#{foo}" } } let(:scope) { stub('scope', foo: 'attribute') } it 'increments within the correct scope' do expect(subject.next(scope)).to eq '=Aattribute' end describe 'when incrementing' do before { subject.next(scope) } it 'increments within the correct scope' do expect(subject.next(scope)).to eq '=Battribute' end end end end factory_girl-4.5.0/spec/factory_girl/registry_spec.rb0000644000004100000410000000436512435642645023104 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Registry do let(:registered_object) { stub("registered object") } let(:second_registered_object) { stub("second registered object") } subject { FactoryGirl::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(ArgumentError, "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 it "registers classes" do define_class("User") subject.register(User, registered_object) expect(subject.to_a).to eq [registered_object] expect(subject.find(:user)).to eq registered_object expect(subject.find(User)).to eq registered_object end end factory_girl-4.5.0/spec/factory_girl/declaration_list_spec.rb0000644000004100000410000000474312435642645024554 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::DeclarationList, "#attributes" do let(:static_attribute_1) { stub("static attribute 1") } let(:static_attribute_2) { stub("static attribute 2") } let(:dynamic_attribute_1) { stub("dynamic attribute 1") } let(:static_declaration) { stub("static declaration", to_attributes: [static_attribute_1, static_attribute_2]) } let(:dynamic_declaration) { stub("static declaration", to_attributes: [dynamic_attribute_1]) } it "returns an AttributeList" do expect(subject.attributes).to be_a(FactoryGirl::AttributeList) end let(:attribute_list) { stub("attribute list", define_attribute: true) } it "defines each attribute on the attribute list" do FactoryGirl::AttributeList.stubs(new: attribute_list) subject.declare_attribute(static_declaration) subject.declare_attribute(dynamic_declaration) subject.attributes expect(attribute_list).to have_received(:define_attribute).with(static_attribute_1) expect(attribute_list).to have_received(:define_attribute).with(static_attribute_2) expect(attribute_list).to have_received(:define_attribute).with(dynamic_attribute_1) end end describe FactoryGirl::DeclarationList, "#declare_attribute" do let(:declaration_1) { stub("declaration", name: "declaration 1") } let(:declaration_2) { stub("declaration", name: "declaration 2") } let(:declaration_with_same_name) { stub("declaration", name: "declaration 1") } 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_girl-4.5.0/spec/factory_girl/aliases_spec.rb0000644000004100000410000000146512435642645022653 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl, "aliases" do context "aliases for an attribute" do subject { FactoryGirl.aliases_for(:test) } it { should include(:test) } it { should include(:test_id) } end context "aliases for a foreign key" do subject { FactoryGirl.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 { FactoryGirl.aliases_for(:_id) } it { should_not include(:id) } end end describe FactoryGirl, "after defining an alias" do before do FactoryGirl.aliases << [/(.*)_suffix/, '\1'] end subject { FactoryGirl.aliases_for(:test_suffix) } it { should include(:test) } it { should include(:test_suffix_id) } end factory_girl-4.5.0/spec/factory_girl/find_definitions_spec.rb0000644000004100000410000000743212435642645024545 0ustar www-datawww-datarequire 'spec_helper' share_examples_for "finds definitions" do before do FactoryGirl.stubs(:load) FactoryGirl.find_definitions end subject { FactoryGirl } 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_for_should 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 FactoryGirl.stubs(:load) sorted_load_order = sequence("load order") FactoryGirl.expects(:load).with(includes("a.rb")).in_sequence(sorted_load_order) FactoryGirl.expects(:load).with(includes("b.rb")).in_sequence(sorted_load_order) FactoryGirl.find_definitions 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_girl-4.5.0/spec/factory_girl/disallows_duplicates_registry_spec.rb0000644000004100000410000000130012435642645027364 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::Decorator::DisallowsDuplicatesRegistry do let(:registry) { stub("registry", name: 'Great thing', register: true) } subject { described_class.new(registry) } it "delegates #register to the registry when not registered" do registry.stubs(registered?: false) subject.register(:awesome, {}) expect(registry).to have_received(:register).with(:awesome, {}) end it "raises when attempting to #register a previously registered strategy" do registry.stubs(registered?: true) expect { subject.register(:same_name, {}) }. to raise_error(FactoryGirl::DuplicateDefinitionError, "Great thing already registered: same_name") end end factory_girl-4.5.0/spec/factory_girl/callback_spec.rb0000644000004100000410000000250112435642645022756 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::Callback do it "has a name" do expect(FactoryGirl::Callback.new(:after_create, -> {}).name).to eq :after_create end it "converts strings to symbols" do expect(FactoryGirl::Callback.new("after_create", -> {}).name).to eq :after_create end it "runs its block with no parameters" do ran_with = nil FactoryGirl::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 FactoryGirl::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 FactoryGirl::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 FactoryGirl.callback_names.each do |callback_name| expect { FactoryGirl::Callback.new(callback_name, -> {}) }. to_not raise_error end end it "raises if an invalid callback name is assigned" do expect { FactoryGirl::Callback.new(:magic_fairies, -> {}) }. to raise_error(FactoryGirl::InvalidCallbackNameError, /magic_fairies is not a valid callback name/) end end factory_girl-4.5.0/spec/factory_girl/evaluator_class_definer_spec.rb0000644000004100000410000000471112435642645026112 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::EvaluatorClassDefiner do it "returns an evaluator when accessing the evaluator class" do evaluator = define_evaluator(parent_class: FactoryGirl::Evaluator) expect(evaluator).to be_a(FactoryGirl::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("dependency", name: :dependency, to_proc: -> { 1 }) 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(FactoryGirl::Strategy::Null) end def define_evaluator_class(arguments = {}) evaluator_class_definer = FactoryGirl::EvaluatorClassDefiner.new( arguments[:attributes] || [], arguments[:parent_class] || FactoryGirl::Evaluator ) evaluator_class_definer.evaluator_class end def stub_attribute(name = :attribute, &value) value ||= -> {} stub(name.to_s, name: name.to_sym, to_proc: value) end end factory_girl-4.5.0/spec/factory_girl/definition_proxy_spec.rb0000644000004100000410000001673612435642645024632 0ustar www-datawww-datarequire 'spec_helper' describe FactoryGirl::DefinitionProxy, "#add_attribute" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject) } it "raises if both a block and value are given" do expect { proxy.add_attribute(:something, "great") { "will raise!" } }.to raise_error(FactoryGirl::AttributeDefinitionError, "Both value and block given") end it "declares a static attribute on the factory" do proxy.add_attribute(:attribute_name, "attribute value") expect(subject).to have_static_declaration(:attribute_name).with_value("attribute value") end 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 FactoryGirl::DefinitionProxy, "#add_attribute when the proxy ignores attributes" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject, true) } it "raises if both a block and value are given" do expect { proxy.add_attribute(:something, "great") { "will raise!" } }.to raise_error(FactoryGirl::AttributeDefinitionError, "Both value and block given") end it "declares a static attribute on the factory" do proxy.add_attribute(:attribute_name, "attribute value") expect(subject).to have_static_declaration(:attribute_name).ignored.with_value("attribute value") end 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 FactoryGirl::DefinitionProxy, "#transient" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject) } it "makes all attributes added ignored" do proxy.transient do add_attribute(:attribute_name, "attribute value") end expect(subject).to have_static_declaration(:attribute_name).ignored.with_value("attribute value") end end describe FactoryGirl::DefinitionProxy, "#method_missing" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject) } it "declares an implicit declaration without args or a block" do proxy.bogus expect(subject).to have_implicit_declaration(:bogus).with_factory(subject) end it "declares an association when :factory is passed" do proxy.author factory: :user expect(subject).to have_association_declaration(:author).with_options(factory: :user) end it "declares a static attribute" do proxy.attribute_name "attribute value" expect(subject).to have_static_declaration(:attribute_name).with_value("attribute value") end 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 describe FactoryGirl::DefinitionProxy, "#sequence" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject) } before { FactoryGirl::Sequence.stubs(:new) } it "creates a new sequence starting at 1" do proxy.sequence(:great) expect(FactoryGirl::Sequence).to have_received(:new).with(:great) end it "creates a new sequence with an overridden starting vaue" do proxy.sequence(:great, "C") expect(FactoryGirl::Sequence).to have_received(:new).with(:great, "C") end it "creates a new sequence with a block" do sequence_block = Proc.new { |n| "user+#{n}@example.com" } proxy.sequence(:great, 1, &sequence_block) expect(FactoryGirl::Sequence).to have_received(:new).with(:great, 1, &sequence_block) end end describe FactoryGirl::DefinitionProxy, "#association" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::DefinitionProxy.new(subject) } it "declares an association" do proxy.association(:association_name) expect(subject).to have_association_declaration(:association_name) end it "declares an association with options" do proxy.association(:association_name, { name: "Awesome" }) expect(subject).to have_association_declaration(:association_name).with_options(name: "Awesome") end end describe FactoryGirl::DefinitionProxy, "adding callbacks" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::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 FactoryGirl::DefinitionProxy, "#to_create" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::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 FactoryGirl::DefinitionProxy, "#factory" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::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 FactoryGirl::DefinitionProxy, "#trait" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::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 FactoryGirl::DefinitionProxy, "#initialize_with" do subject { FactoryGirl::Definition.new } let(:proxy) { FactoryGirl::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_girl-4.5.0/spec/factory_girl/definition_spec.rb0000644000004100000410000000343612435642645023362 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl::Definition do it { should delegate(:declare_attribute).to(:declarations) } end describe FactoryGirl::Definition, "with a name" do let(:name) { :"great name" } subject { FactoryGirl::Definition.new(name) } it "creates a new attribute list with the name passed" do FactoryGirl::DeclarationList.stubs(:new) subject expect(FactoryGirl::DeclarationList).to have_received(:new).with(name) end end describe FactoryGirl::Definition, "#overridable" do let(:list) { stub("declaration list", overridable: true) } before { FactoryGirl::DeclarationList.stubs(new: list) } it "sets the declaration list as overridable" do expect(subject.overridable).to eq subject expect(list).to have_received(:overridable).once end end describe FactoryGirl::Definition, "defining traits" do let(:trait_1) { stub("trait") } let(:trait_2) { stub("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 FactoryGirl::Definition, "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 FactoryGirl::Definition, "#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 factory_girl-4.5.0/spec/support/0000755000004100000410000000000012435642645016715 5ustar www-datawww-datafactory_girl-4.5.0/spec/support/macros/0000755000004100000410000000000012435642645020201 5ustar www-datawww-datafactory_girl-4.5.0/spec/support/macros/define_constant.rb0000644000004100000410000000405412435642645023674 0ustar www-datawww-datarequire 'active_record' module DefineConstantMacros def define_class(path, base = Object, &block) namespace, class_name = *constant_path(path) klass = Class.new(base) namespace.const_set(class_name, klass) klass.class_eval(&block) if block_given? @defined_constants << path klass 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 connection.execute("DROP TABLE IF EXISTS #{table_name}") raise exception end end def constant_path(constant_name) names = constant_name.split('::') class_name = names.pop namespace = names.inject(Object) { |result, name| result.const_get(name) } [namespace, class_name] end def default_constants @defined_constants ||= [] @created_tables ||= [] end def clear_generated_constants @defined_constants.reverse.each do |path| namespace, class_name = *constant_path(path) namespace.send(:remove_const, class_name) end @defined_constants.clear end def clear_generated_tables @created_tables.each do |table_name| ActiveRecord::Base. connection. execute("DROP TABLE IF EXISTS #{table_name}") end @created_tables.clear end end RSpec.configure do |config| config.include DefineConstantMacros config.before(:all) do ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: File.join(File.dirname(__FILE__), 'test.db') ) end config.before do default_constants end config.after do clear_generated_constants clear_generated_tables end end factory_girl-4.5.0/spec/support/matchers/0000755000004100000410000000000012435642645020523 5ustar www-datawww-datafactory_girl-4.5.0/spec/support/matchers/trait.rb0000644000004100000410000000037712435642645022202 0ustar www-datawww-dataRSpec::Matchers.define :have_trait do |trait_name| match do |instance| instance.defined_traits.any? do |trait| trait.name == trait_name && trait.send(:block) == @block end end chain :with_block do |block| @block = block end end factory_girl-4.5.0/spec/support/matchers/declaration.rb0000644000004100000410000000342612435642645023342 0ustar www-datawww-datamodule DeclarationMatchers def have_static_declaration(name) DeclarationMatcher.new(:static).named(name) end 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 :static then FactoryGirl::Declaration::Static.new(@name, @value, ignored?) when :dynamic then FactoryGirl::Declaration::Dynamic.new(@name, ignored?, @value) when :implicit then FactoryGirl::Declaration::Implicit.new(@name, @factory, ignored?) when :association if @options FactoryGirl::Declaration::Association.new(@name, options) else FactoryGirl::Declaration::Association.new(@name) end end end def ignored? !!@ignored end def options @options || {} end end end factory_girl-4.5.0/spec/support/matchers/callback.rb0000644000004100000410000000034412435642645022605 0ustar www-datawww-dataRSpec::Matchers.define :have_callback do |callback_name| match do |instance| instance.callbacks.include?(FactoryGirl::Callback.new(callback_name, @block)) end chain :with_block do |block| @block = block end end factory_girl-4.5.0/spec/support/matchers/delegate.rb0000644000004100000410000000212712435642645022624 0ustar www-datawww-dataRSpec::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| extend Mocha::API @instance = instance @args ||= [] return_value = 'stubbed return value' method_on_target = @method_on_target || delegated_method stubbed_target = stub('stubbed_target', method_on_target => return_value) @instance.stubs(@target_method => stubbed_target) begin @instance.send(delegated_method, *@args) == return_value rescue NoMethodError false end end failure_message_for_should 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_girl-4.5.0/spec/support/shared_examples/0000755000004100000410000000000012435642645022061 5ustar www-datawww-datafactory_girl-4.5.0/spec/support/shared_examples/strategy.rb0000644000004100000410000000556112435642645024257 0ustar www-datawww-datashared_examples_for "strategy without association support" do let(:factory) { stub("associate_factory") } let(:attribute) { FactoryGirl::Attribute::Association.new(:user, :user, {}) } def association_named(name, overrides) runner = FactoryGirl::FactoryRunner.new(name, :build, [overrides]) subject.association(runner) end before do FactoryGirl.stubs(factory_by_name: factory) factory.stubs(:compile) factory.stubs(: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_girl_strategy_name| let(:factory) { stub("associate_factory") } def association_named(name, strategy, overrides) runner = FactoryGirl::FactoryRunner.new(name, strategy, [overrides]) subject.association(runner) end before do FactoryGirl.stubs(factory_by_name: factory) factory.stubs(:compile) factory.stubs(:run) end it "runs the factory with the correct overrides" do association_named(:author, factory_girl_strategy_name, great: "value") expect(factory).to have_received(:run).with(factory_girl_strategy_name, great: "value") end it "finds the factory with the correct factory name" do association_named(:author, factory_girl_strategy_name, great: "value") expect(FactoryGirl).to have_received(:factory_by_name).with(:author) end end shared_examples_for "strategy with strategy: :build" do |factory_girl_strategy_name| let(:factory) { stub("associate_factory") } def association_named(name, overrides) runner = FactoryGirl::FactoryRunner.new(name, overrides[:strategy], [overrides.except(:strategy)]) subject.association(runner) end before do FactoryGirl.stubs(factory_by_name: factory) factory.stubs(:compile) factory.stubs(: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_girl_strategy_name, { great: "value" }) end it "finds the factory with the correct factory name" do association_named(:author, strategy: :build, great: "value") expect(FactoryGirl).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) { stub("evaluation", object: result_instance, notify: true, create: nil) } 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 factory_girl-4.5.0/spec/acceptance/0000755000004100000410000000000012435642645017267 5ustar www-datawww-datafactory_girl-4.5.0/spec/acceptance/sequence_context_spec.rb0000644000004100000410000000255212435642645024206 0ustar www-datawww-datarequire 'spec_helper' describe '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 FactoryGirl.define do factory :sequence_with_sprintf, class: User do sequence(:id) { |n| sprintf("foo%d", n) } end end expect(FactoryGirl.build(:sequence_with_sprintf).id).to eq 'foo1' end it 'invokes the correct method on the instance' do FactoryGirl.define do factory :sequence_with_public_method, class: User do sequence(:id) { |n| public_method(:awesome).call } end end expect(FactoryGirl.build(:sequence_with_public_method).id).to eq 'aw yeah' end it 'invokes a method with no arguments on the instance' do FactoryGirl.define do factory :sequence_with_frozen, class: User do sequence(:id) { |n| frozen? } end end expect(FactoryGirl.build(:sequence_with_frozen).id).to be_false end it 'allows direct reference of a method in a sequence' do FactoryGirl.define do factory :sequence_referencing_attribute_directly, class: User do sequence(:id) { |n| "#{awesome}#{n}" } end end expect(FactoryGirl.build(:sequence_referencing_attribute_directly).id).to eq 'aw yeah1' end end factory_girl-4.5.0/spec/acceptance/initialize_with_spec.rb0000644000004100000410000001127212435642645024025 0ustar www-datawww-datarequire "spec_helper" describe "initialize_with with non-FG attributes" do include FactoryGirl::Syntax::Methods before do define_model("User", name: :string, age: :integer) do def self.construct(name, age) new(name: name, age: age) end end FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_model("User", name: :string) do def self.construct(name) new(name: "#{name} from .construct") end end FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_class("ReportGenerator") do attr_reader :name, :data def initialize(name, data) @name = name @data = data end end FactoryGirl.define do sequence(:random_data) { 5.times.map { Kernel.rand(200) } } factory :report_generator do transient do name "My Awesome Report" end initialize_with { ReportGenerator.new(name, FactoryGirl.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 FactoryGirl.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(FactoryGirl.build(:sub_awesome).name).to eq "Sub" end it "allows child factories to override initialize_with" do expect(FactoryGirl.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 FactoryGirl.define do factory :awesome do transient do name "Great" end initialize_with { new(name) } end end end it "instantiates the correct object" do expect(FactoryGirl.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 FactoryGirl.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 = FactoryGirl.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 before do define_class("User") do attr_reader :name, :email, :ignored def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] @ignored = attributes[:ignored] end end FactoryGirl.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 end it "assigns attributes correctly" do user_with_attributes = FactoryGirl.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 factory_girl-4.5.0/spec/acceptance/nested_attributes_spec.rb0000644000004100000410000000157712435642645024370 0ustar www-datawww-datarequire "spec_helper" describe "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 FactoryGirl.define do factory :post do comments_attributes { [FactoryGirl.attributes_for(:comment), FactoryGirl.attributes_for(:comment)] } end factory :comment do sequence(:body) { |n| "Body #{n}" } end end end it "assigns the correct amount of comments" do expect(FactoryGirl.create(:post).comments.count).to eq 2 end it "assigns the correct amount of comments when overridden" do expect(FactoryGirl.create(:post, :comments_attributes => [FactoryGirl.attributes_for(:comment)]).comments.count).to eq 1 end end factory_girl-4.5.0/spec/acceptance/modify_inherited_spec.rb0000644000004100000410000000253412435642645024154 0ustar www-datawww-datarequire "spec_helper" describe "modifying inherited factories with traits" do before do define_model('User', gender: :string, admin: :boolean, age: :integer) FactoryGirl.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(FactoryGirl.build(:male_user).gender).to eq "Male" end it "returns the correct value for overridden attributes from traits defining multiple attributes" do expect(FactoryGirl.build(:female_user).gender).to eq "Female" expect(FactoryGirl.build(:female_user).age).to eq 25 expect(FactoryGirl.build(:female_user).admin).to eq true end it "allows modification of attributes created via traits" do FactoryGirl.modify do factory :male_user do age 20 end end expect(FactoryGirl.build(:male_user).gender).to eq "Male" expect(FactoryGirl.build(:male_user).age).to eq 20 expect(FactoryGirl.build(:male_user).admin).to eq true end end factory_girl-4.5.0/spec/acceptance/create_spec.rb0000644000004100000410000000421512435642645022073 0ustar www-datawww-datarequire 'spec_helper' describe "a created instance" do include FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_class('User') do def initialize @persisted = false end def persist @persisted = true end def persisted? @persisted end end FactoryGirl.define do factory :user do to_create do |user| user.persist end end end end it "uses the custom create block instead of save" do expect(FactoryGirl.create(:user)).to be_persisted end end describe "calling `create` with a block" do include FactoryGirl::Syntax::Methods before do define_model('Company', name: :string) FactoryGirl.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_girl-4.5.0/spec/acceptance/build_stubbed_spec.rb0000644000004100000410000000751612435642645023446 0ustar www-datawww-datarequire 'spec_helper' describe "a generated stub instance" do include FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', title: :string, body: :string, age: :integer, user_id: :integer) do belongs_to :user end FactoryGirl.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).not_to be_nil 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 "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 end describe "calling `build_stubbed` with a block" do include FactoryGirl::Syntax::Methods before do define_model('Company', name: :string) FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_model('ThingWithTimestamp', created_at: :datetime) define_model('ThingWithoutTimestamp') FactoryGirl.define do factory :thing_with_timestamp factory :thing_without_timestamp end Timecop.freeze 2012, 1, 1 end it "defaults created_at for objects with created_at" do expect(build_stubbed(:thing_with_timestamp).created_at).to eq Time.now end it "defaults created_at for objects with created_at to the correct time with zone" do original_timezone = ENV['TZ'] ENV['TZ'] = 'UTC' Time.zone = 'Eastern Time (US & Canada)' expect(build_stubbed(:thing_with_timestamp).created_at.zone).to eq 'EST' ENV['TZ'] = original_timezone end it "adds created_at to objects who don't have the method" do expect(build_stubbed(:thing_without_timestamp)).to respond_to(:created_at) end it "allows overriding created_at for objects with created_at" do expect(build_stubbed(:thing_with_timestamp, created_at: 3.days.ago).created_at).to eq 3.days.ago 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 end describe 'defaulting `id`' do before do define_model('Post') FactoryGirl.define do factory :post end end it 'allows overriding id' do expect(FactoryGirl.build_stubbed(:post, id: 12).id).to eq 12 end end factory_girl-4.5.0/spec/acceptance/attribute_existing_on_object_spec.rb0000644000004100000410000000342012435642645026564 0ustar www-datawww-datarequire "spec_helper" describe "declaring attributes on a Factory that are private methods on Object" do before do define_model("Website", system: :boolean, link: :string, sleep: :integer) FactoryGirl.define do factory :website do system false link "http://example.com" sleep 15 end end end subject { FactoryGirl.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 FactoryGirl.define do factory :website do more_format { "format: #{format}" } end end end after do Object.send(:undef_method, :some_funky_method) end subject { FactoryGirl.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 FactoryGirl.define do factory :website do more_format { "format: #{format}" } end end end subject { FactoryGirl.build(:website) } its(:more_format) { should eq "format: This is an awesome format" } end factory_girl-4.5.0/spec/acceptance/global_to_create_spec.rb0000644000004100000410000000614512435642645024121 0ustar www-datawww-datarequire 'spec_helper' describe 'global to_create' do before do define_model('User', name: :string) define_model('Post', name: :string) FactoryGirl.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(FactoryGirl.create(:user).name).to eq 'persisted!' expect(FactoryGirl.create(:post).name).to eq 'persisted!' end it 'handles child to_create' do expect(FactoryGirl.create(:child_user).name).to eq 'persisted!' expect(FactoryGirl.create(:child_post).name).to eq 'persisted!' end it 'handles child to_create with trait' do expect(FactoryGirl.create(:child_user_with_trait).name).to eq 'override' expect(FactoryGirl.create(:child_post_with_trait).name).to eq 'override' end it 'handles inline trait override' do expect(FactoryGirl.create(:child_user, :override_to_create).name).to eq 'override' expect(FactoryGirl.create(:child_post, :override_to_create).name).to eq 'override' end it 'uses to_create globally across FactoryGirl.define' do define_model('Company', name: :string) FactoryGirl.define do factory :company end expect(FactoryGirl.create(:company).name).to eq 'persisted!' expect(FactoryGirl.create(:company, :override_to_create).name).to eq 'override' end end describe 'global skip_create' do before do define_model('User', name: :string) define_model('Post', name: :string) FactoryGirl.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(FactoryGirl.create(:user)).to be_new_record expect(FactoryGirl.create(:post)).to be_new_record end it 'does not persist child records' do expect(FactoryGirl.create(:child_user)).to be_new_record expect(FactoryGirl.create(:child_post)).to be_new_record end it 'honors overridden to_create' do expect(FactoryGirl.create(:child_user_with_trait).name).to eq 'override' expect(FactoryGirl.create(:child_post_with_trait).name).to eq 'override' end it 'honors inline trait to_create' do expect(FactoryGirl.create(:child_user, :override_to_create).name).to eq 'override' expect(FactoryGirl.create(:child_post, :override_to_create).name).to eq 'override' end end factory_girl-4.5.0/spec/acceptance/register_strategies_spec.rb0000644000004100000410000000663412435642645024715 0ustar www-datawww-datarequire "spec_helper" shared_context "registering custom strategies" do before do define_class("NamedObject") do attr_accessor :name end end let(:custom_strategy) do Class.new do def result(evaluation) evaluation.object.tap do |instance| instance.name = "Custom strategy" end end end end end describe "register custom strategies" do include_context "registering custom strategies" before do FactoryGirl.define do factory :named_object do name "Great" end end end it "allows overriding default strategies" do expect(FactoryGirl.build(:named_object).name).to eq "Great" FactoryGirl.register_strategy(:build, custom_strategy) expect(FactoryGirl.build(:named_object).name).to eq "Custom strategy" end it "allows adding additional strategies" do FactoryGirl.register_strategy(:insert, custom_strategy) expect(FactoryGirl.build(:named_object).name).to eq "Great" expect(FactoryGirl.insert(:named_object).name).to eq "Custom strategy" end it "allows using the *_list method to build a list using a custom strategy" do FactoryGirl.register_strategy(:insert, custom_strategy) inserted_items = FactoryGirl.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 FactoryGirl.register_strategy(:insert, custom_strategy) inserted_items = FactoryGirl.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 FactoryGirl::Syntax::Methods when custom strategies have been declared" do include FactoryGirl::Syntax::Methods include_context "registering custom strategies" before do FactoryGirl.define do factory :named_object do name "Great" end end end it "allows adding additional strategies" do FactoryGirl.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) FactoryGirl.define do factory :post do user end factory :user do name "John Doe" end end end it "uses the overridden create strategy to create the association" do FactoryGirl.register_strategy(:create, custom_strategy) post = FactoryGirl.build(:post) expect(post.user.name).to eq "Custom strategy" 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) FactoryGirl.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 FactoryGirl.register_strategy(:insert, custom_strategy) post = FactoryGirl.build(:post) expect(post.user.name).to eq "Custom strategy" end end factory_girl-4.5.0/spec/acceptance/lint_spec.rb0000644000004100000410000000273112435642645021577 0ustar www-datawww-datarequire 'spec_helper' describe 'FactoryGirl.lint' do it 'raises when a factory is invalid' do define_model 'User', name: :string do validates :name, presence: true end define_model 'AlwaysValid' FactoryGirl.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 FactoryGirl.lint end.to raise_error FactoryGirl::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 FactoryGirl.define do factory :user do name 'assigned' end end expect { FactoryGirl.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 FactoryGirl.define do factory :valid_thing factory :invalid_thing end expect do only_valid_factories = FactoryGirl.factories.reject do |factory| factory.name =~ /invalid/ end FactoryGirl.lint only_valid_factories end.not_to raise_error end end factory_girl-4.5.0/spec/acceptance/define_child_before_parent_spec.rb0000644000004100000410000000073112435642645026117 0ustar www-datawww-datarequire "spec_helper" describe "defining a child factory before a parent" do before do define_model("User", name: :string, admin: :boolean, email: :string, upper_email: :string, login: :string) FactoryGirl.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(FactoryGirl.create(:admin)).to be_admin end end factory_girl-4.5.0/spec/acceptance/build_spec.rb0000644000004100000410000000312512435642645021726 0ustar www-datawww-datarequire 'spec_helper' describe "a built instance" do include FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.define do factory :user factory :post do user 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 "a built instance with strategy: :build" do include FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.define do factory :user factory :post do association(:user, strategy: :build) end end end subject { build(:post) } it { should be_new_record } it "assigns but does not save associations" do expect(subject.user).to be_kind_of(User) expect(subject.user).to be_new_record end end describe "calling `build` with a block" do include FactoryGirl::Syntax::Methods before do define_model('Company', name: :string) FactoryGirl.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_girl-4.5.0/spec/acceptance/attributes_from_instance_spec.rb0000644000004100000410000000267012435642645025730 0ustar www-datawww-datarequire "spec_helper" describe "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 FactoryGirl.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(FactoryGirl.build(:user).age_copy).to eq 18 end it "returns nil during attributes_for" do expect(FactoryGirl.attributes_for(:user)[:age_copy]).to be_nil end it "doesn't instantiate a record with attributes_for" do User.stubs(:new) FactoryGirl.attributes_for(:user) expect(User).to have_received(:new).never end end context "with the attribute being overridden" do it "uses the overridden value" do expect(FactoryGirl.build(:user, age_copy: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryGirl.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(FactoryGirl.build(:user, age: nil).age_copy).to be_nil end it "uses the overridden value during attributes_for" do expect(FactoryGirl.attributes_for(:user, age: 25)[:age_copy]).to eq 25 end end end factory_girl-4.5.0/spec/acceptance/definition_camel_string_spec.rb0000644000004100000410000000055212435642645025507 0ustar www-datawww-datarequire 'spec_helper' describe "an instance generated by a factory named a camel case string " do before do define_model("UserModel") FactoryGirl.define do factory 'UserModel', class: UserModel end end it "registers the UserModel factory" do expect(FactoryGirl.factory_by_name('UserModel')).to be_a(FactoryGirl::Factory) end end factory_girl-4.5.0/spec/acceptance/attributes_for_spec.rb0000644000004100000410000000417112435642645023665 0ustar www-datawww-datarequire 'spec_helper' describe "a generated attributes hash" do include FactoryGirl::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 FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_model('Company', name: :string) FactoryGirl.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 FactoryGirl.define do factory :user do name "John Doe" end end end subject { FactoryGirl.attributes_for(:user) } its([:name]) { should eq "John Doe" } end factory_girl-4.5.0/spec/acceptance/traits_spec.rb0000644000004100000410000004720012435642645022137 0ustar www-datawww-datarequire "spec_helper" describe "an instance generated by a factory with multiple traits" do before do define_model("User", name: :string, admin: :boolean, gender: :string, email: :string, date_of_birth: :date, great: :string) FactoryGirl.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 :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 :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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.create(:male_user) } its(:gender) { should eq "Male" } end context "factory created with alternate syntax where trait name and attribute are the same" do subject { FactoryGirl.create(:great_user) } its(:great) { should eq "GREAT!!!" } end context "factory created with alternate syntax where trait name and attribute are the same and attribute is overridden" do subject { FactoryGirl.create(:great_user, great: "SORT OF!!!") } its(:great) { should eq "SORT OF!!!" } end context "child factory created where trait attributes are inherited" do subject { FactoryGirl.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 { FactoryGirl.create(:user_without_admin_scoping) } it { expect { subject }.to raise_error(ArgumentError, "Trait not registered: admin_trait") } end context "child factory using grandparents' trait" do subject { FactoryGirl.create(:female_great_user) } its(:great) { should eq "GREAT!!!" } end end describe "traits with callbacks" do before do define_model("User", name: :string) FactoryGirl.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 { FactoryGirl.create(:caps_user) } its(:name) { should eq "JOHN" } end context "when the factory has an implicit trait" do subject { FactoryGirl.create(:caps_user_implicit_trait) } its(:name) { should eq "JOHN" } end it "executes callbacks in the order assigned" do expect(FactoryGirl.create(:awesome_user).name).to eq "awesome" end end describe "traits added via strategy" do before do define_model("User", name: :string, admin: :boolean) FactoryGirl.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 { FactoryGirl.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(FactoryGirl.create(:user)).not_to be_admin expect(FactoryGirl.create(:user).name).to eq "John" end end context "adding traits in build" do subject { FactoryGirl.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 { FactoryGirl.attributes_for(:user, :admin, :great) } its([:admin]) { should be_true } its([:name]) { should eq "John" } end context "adding traits in build_stubbed" do subject { FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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) FactoryGirl.define do trait :email do email { "#{name}@example.com" } end factory :user do name "John" email combined { "#{name} <#{email}>" } end end end subject { FactoryGirl.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 FactoryGirl.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(FactoryGirl.create(:user, :with_post).posts).not_to be_empty expect(FactoryGirl.create(:user).posts).to be_empty expect(FactoryGirl.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) FactoryGirl.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(FactoryGirl.build(:user).status).to eq "pending" end it "prefers inline trait attributes over default attributes" do expect(FactoryGirl.build(:user, :accepted).status).to eq "accepted" end it "prefers traits on a factory over default attributes" do expect(FactoryGirl.build(:declined_user).status).to eq "declined" end it "prefers inline trait attributes over traits on a factory" do expect(FactoryGirl.build(:declined_user, :accepted).status).to eq "accepted" end it "prefers attributes on factories over attributes from non-inline traits" do expect(FactoryGirl.build(:extended_declined_user).status).to eq "extended_declined" end it "prefers inline traits over attributes on factories" do expect(FactoryGirl.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 expect(FactoryGirl.build(:extended_declined_user, :accepted, status: "completely overridden").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) FactoryGirl.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 = FactoryGirl.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) FactoryGirl.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(FactoryGirl.create(:user, :with_to_create).name).to eq "to_create" end it "can apply to_create from the definition" do expect(FactoryGirl.create(:sub_user).name).to eq "sub" expect(FactoryGirl.create(:child_user).name).to eq "sub" end it "gives additional traits higher priority than to_create from the definition" do expect(FactoryGirl.create(:sub_user, :with_to_create).name).to eq "to_create" expect(FactoryGirl.create(:child_user, :with_to_create).name).to eq "to_create" end it "gives base traits normal priority" do expect(FactoryGirl.create(:sub_user_with_trait).name).to eq "to_create" expect(FactoryGirl.create(:child_user_with_trait).name).to eq "to_create" end it "gives base traits lower priority than overrides" do expect(FactoryGirl.create(:sub_user_with_trait_and_override).name).to eq "sub with trait and override" expect(FactoryGirl.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 FactoryGirl.define do trait :overridden do to_create { |instance| instance.name = "completely overridden" } end end expect(FactoryGirl.create(:sub_user_with_trait_and_override, :overridden).name).to eq "completely overridden" expect(FactoryGirl.create(:child_user_with_trait_and_override, :overridden).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 FactoryGirl.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(FactoryGirl.build(:user, :with_initialize_with).name).to eq "initialize_with" end it "can apply initialize_with from the definition" do expect(FactoryGirl.build(:sub_user).name).to eq "sub" expect(FactoryGirl.build(:child_user).name).to eq "sub" end it "gives additional traits higher priority than initialize_with from the definition" do expect(FactoryGirl.build(:sub_user, :with_initialize_with).name).to eq "initialize_with" expect(FactoryGirl.build(:child_user, :with_initialize_with).name).to eq "initialize_with" end it "gives base traits normal priority" do expect(FactoryGirl.build(:sub_user_with_trait).name).to eq "initialize_with" expect(FactoryGirl.build(:child_user_with_trait).name).to eq "initialize_with" end it "gives base traits lower priority than overrides" do expect(FactoryGirl.build(:sub_user_with_trait_and_override).name).to eq "sub with trait and override" expect(FactoryGirl.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 FactoryGirl.define do trait :overridden do initialize_with { new("completely overridden") } end end expect(FactoryGirl.build(:sub_user_with_trait_and_override, :overridden).name).to eq "completely overridden" expect(FactoryGirl.build(:child_user_with_trait_and_override, :overridden).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 = FactoryGirl.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 FactoryGirl.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 FactoryGirl.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) FactoryGirl.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(FactoryGirl.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 FactoryGirl.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 = FactoryGirl.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 = FactoryGirl.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 = FactoryGirl.create(:order).creator expect(creator).to be_admin expect(creator.name).to eq 'Joe Creator' end end factory_girl-4.5.0/spec/acceptance/create_list_spec.rb0000644000004100000410000000443412435642645023131 0ustar www-datawww-datarequire 'spec_helper' describe "create multiple instances" do before do define_model('Post', title: :string, position: :integer) FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 FactoryGirl.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_with_index do |record, index| expect(record.position).to eq record.id end 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 FactoryGirl.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| FactoryGirl.create_list(:post, evaluator.posts_count, user: user) end end end end end it "generates the correct number of posts" do expect(FactoryGirl.create(:user_with_posts).posts.length).to eq 5 end it "allows the number of posts to be modified" do expect(FactoryGirl.create(:user_with_posts, posts_count: 2).posts.length).to eq 2 end end factory_girl-4.5.0/spec/acceptance/stub_spec.rb0000644000004100000410000000231512435642645021604 0ustar www-datawww-datarequire 'spec_helper' describe "a stubbed instance" do include FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.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 FactoryGirl::Syntax::Methods before do define_model('User') define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.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 factory_girl-4.5.0/spec/acceptance/overrides_spec.rb0000644000004100000410000000253712435642645022637 0ustar www-datawww-datarequire 'spec_helper' describe "attribute overrides" do before do define_model('User', admin: :boolean) define_model('Post', title: :string, secure: :boolean, user_id: :integer) do belongs_to :user def secure=(value) return unless user && user.admin? write_attribute(:secure, value) end end FactoryGirl.define do factory :user do factory :admin do admin true end end factory :post do user title "default title" end end end let(:admin) { FactoryGirl.create(:admin) } let(:post_attributes) do { secure: false } end let(:non_admin_post_attributes) do post_attributes[:user] = FactoryGirl.create(:user) post_attributes end let(:admin_post_attributes) do post_attributes[:user] = admin post_attributes end context "with an admin posting" do subject { FactoryGirl.create(:post, admin_post_attributes) } its(:secure) { should eq false } end context "with a non-admin posting" do subject { FactoryGirl.create(:post, non_admin_post_attributes) } its(:secure) { should be_nil } end context "with no user posting" do subject { FactoryGirl.create(:post, post_attributes) } its(:secure) { should be_nil } end end factory_girl-4.5.0/spec/acceptance/attributes_ordered_spec.rb0000644000004100000410000000305412435642645024522 0ustar www-datawww-datarequire 'spec_helper' describe "a generated attributes hash where order matters" do include FactoryGirl::Syntax::Methods before do define_model('ParentModel', static: :integer, evaluates_first: :integer, evaluates_second: :integer, evaluates_third: :integer) FactoryGirl.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 { FactoryGirl.build(:child_model) } it "assigns attributes in the order they're defined with preference to static attributes" 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 { FactoryGirl.build(:without_parent) } it "assigns attributes in the order they're defined with preference to static attributes 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_girl-4.5.0/spec/acceptance/parent_spec.rb0000644000004100000410000000501512435642645022120 0ustar www-datawww-datarequire 'spec_helper' describe "an instance generated by a factory that inherits from another factory" do before do define_model("User", name: :string, admin: :boolean, email: :string, upper_email: :string, login: :string) FactoryGirl.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 factory :guest do email { "#{name}-guest@example.com" } end factory :no_email do email "" end factory :bill do name { "Bill" } #block to make attribute dynamic end end end end describe "the parent class" do subject { FactoryGirl.create(:user) } it { should_not be_admin } its(:email) { should eq "john@example.com" } end describe "the child class redefining parent's static method used by a dynamic method" do subject { FactoryGirl.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(:upper_email) { should eq "ADMIN@EXAMPLE.COM"} end describe "the child class redefining parent's dynamic method" do subject { FactoryGirl.create(:guest) } it { should_not be_admin } its(:name) { should eq "John" } its(:email) { should eql "John-guest@example.com" } its(:login) { should eq "John-guest@example.com" } end describe "the child class redefining parent's dynamic attribute with static attribute" do subject { FactoryGirl.create(:no_email) } its(:email) { should eq "" } end describe "the child class redefining parent's static attribute with dynamic attribute" do subject { FactoryGirl.create(:bill) } its(:name) { should eq "Bill" } end end describe "nested factories with different parents" do before do define_model("User", name: :string) FactoryGirl.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(FactoryGirl.build(:uppercase_male_user).name).to eq "JOHN DOE" end end factory_girl-4.5.0/spec/acceptance/build_list_spec.rb0000644000004100000410000000252512435642645022764 0ustar www-datawww-datarequire 'spec_helper' describe "build multiple instances" do before do define_model('Post', title: :string, position: :integer) FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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 FactoryGirl.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_with_index do |record, index| expect(record.position).to eq record.id end end end end factory_girl-4.5.0/spec/acceptance/sequence_spec.rb0000644000004100000410000000323012435642645022434 0ustar www-datawww-datarequire 'spec_helper' describe "sequences" do include FactoryGirl::Syntax::Methods it "generates several values in the correct format" do FactoryGirl.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 FactoryGirl.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 FactoryGirl.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 FactoryGirl.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 end factory_girl-4.5.0/spec/acceptance/definition_without_block_spec.rb0000644000004100000410000000044712435642645025720 0ustar www-datawww-datarequire 'spec_helper' describe "an instance generated by a factory" do before do define_model("User") FactoryGirl.define do factory :user end end it "registers the user factory" do expect(FactoryGirl.factory_by_name(:user)).to be_a(FactoryGirl::Factory) end end factory_girl-4.5.0/spec/acceptance/defining_methods_inside_a_factory_spec.rb0000644000004100000410000000070212435642645027515 0ustar www-datawww-datarequire 'spec_helper' describe 'defining methods inside FactoryGirl' do it 'raises with a meaningful message' do define_model('User') expect do FactoryGirl.define do factory :user do def generate_name 'John Doe' end end end end.to raise_error FactoryGirl::MethodDefinitionError, /Defining methods in blocks \(trait or factory\) is not supported \(generate_name\)/ end end factory_girl-4.5.0/spec/acceptance/transient_attributes_spec.rb0000644000004100000410000001025512435642645025106 0ustar www-datawww-datarequire "spec_helper" describe "transient attributes" do before do define_model("User", name: :string, email: :string) FactoryGirl.define do sequence(:name) { |n| "John #{n}" } factory :user do transient do four { 2 + 2 } rockstar true upcased false end name { "#{FactoryGirl.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 { FactoryGirl.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) { FactoryGirl.create(:user, rockstar: true, four: "1234") } let(:rockstar_with_name) { FactoryGirl.create(:user, name: "Jane Doe", rockstar: true) } let(:upcased_rockstar) { FactoryGirl.create(:user, rockstar: true, upcased: true) } let(:groupie) { FactoryGirl.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) { FactoryGirl.create(:user) } it "uses the default value of the attribute" do expect(rockstar.name).to eq "John 1 - Rockstar" end end context "using aliased 'ignore' method name" do around do |example| cached_silenced = ActiveSupport::Deprecation.silenced ActiveSupport::Deprecation.silenced = true example.run ActiveSupport::Deprecation.silenced = cached_silenced end before do FactoryGirl.define do factory :user_using_ignore, class: User do ignore do honorific "Esteemed" end name { "#{honorific} Jane Doe" } end end end let(:esteemed) { FactoryGirl.create(:user_using_ignore) } it "uses the default value of the attribute" do expect(esteemed.name).to eq "Esteemed Jane Doe" end end end describe "transient sequences" do before do define_model("User", name: :string) FactoryGirl.define do factory :user do transient do sequence(:counter) end name { "John Doe #{counter}" } end end end it "increments sequences correctly" do expect(FactoryGirl.build(:user).name).to eq "John Doe 1" expect(FactoryGirl.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 FactoryGirl.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 = FactoryGirl.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_girl-4.5.0/spec/acceptance/global_initialize_with_spec.rb0000644000004100000410000000404212435642645025342 0ustar www-datawww-datarequire 'spec_helper' describe 'global initialize_with' do before do define_class('User') do attr_accessor:name def initialize(name) @name = name end end define_class('Post') do attr_reader :name def initialize(name) @name = name end end FactoryGirl.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(FactoryGirl.build(:user).name).to eq 'initialize_with' expect(FactoryGirl.build(:post).name).to eq 'initialize_with' end it 'handles child initialize_with' do expect(FactoryGirl.build(:child_user).name).to eq 'initialize_with' expect(FactoryGirl.build(:child_post).name).to eq 'initialize_with' end it 'handles child initialize_with with trait' do expect(FactoryGirl.build(:child_user_with_trait).name).to eq 'trait initialize_with' expect(FactoryGirl.build(:child_post_with_trait).name).to eq 'trait initialize_with' end it 'handles inline trait override' do expect(FactoryGirl.build(:child_user, :with_initialize_with).name).to eq 'trait initialize_with' expect(FactoryGirl.build(:child_post, :with_initialize_with).name).to eq 'trait initialize_with' end it 'uses initialize_with globally across FactoryGirl.define' do define_class('Company') do attr_reader :name def initialize(name) @name = name end end FactoryGirl.define do factory :company end expect(FactoryGirl.build(:company).name).to eq 'initialize_with' expect(FactoryGirl.build(:company, :with_initialize_with).name).to eq 'trait initialize_with' end end factory_girl-4.5.0/spec/acceptance/aliases_spec.rb0000644000004100000410000000061212435642645022246 0ustar www-datawww-datarequire "spec_helper" describe "aliases and overrides" do before do FactoryGirl.aliases << [/one/, "two"] define_model("User", two: :string, one: :string) FactoryGirl.define do factory :user do two "set value" end end end subject { FactoryGirl.create(:user, one: "override") } its(:one) { should eq "override" } its(:two) { should be_nil } end factory_girl-4.5.0/spec/acceptance/keyed_by_class_spec.rb0000644000004100000410000000103312435642645023603 0ustar www-datawww-datarequire 'spec_helper' describe 'finding factories keyed by class instead of symbol' do before do define_model("User") do attr_accessor :name, :email end FactoryGirl.define do factory :user do name 'John Doe' sequence(:email) { |n| "person#{n}@example.com" } end end end it 'allows interaction based on class name' do user = FactoryGirl.create User, email: 'person@example.com' expect(user.email).to eq 'person@example.com' expect(user.name).to eq 'John Doe' end end factory_girl-4.5.0/spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb0000644000004100000410000000262512435642645031240 0ustar www-datawww-datarequire "spec_helper" describe "syntax methods within dynamic attributes" do before do define_model("Post", title: :string, user_id: :integer) do belongs_to :user def generate "generate result" end end define_model("User", email: :string) FactoryGirl.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(FactoryGirl.build(:user).email).to eq "person-1@example.com" expect(FactoryGirl.attributes_for(:user)[:email]).to eq "person-2@example.com" end it "can access syntax methods from dynamic attributes" do expect(FactoryGirl.build(:post).user).to be_instance_of(User) end it "can access methods already existing on the class" do expect(FactoryGirl.build(:post).title).to eq "generate result" expect(FactoryGirl.attributes_for(:post)[:title]).to be_nil end it 'allows syntax methods to be used when the block has an arity of 1' do FactoryGirl.define do factory :post_using_block_with_variable, parent: :post do user { |_| build(:user) } end end expect(FactoryGirl.build(:post_using_block_with_variable).user).to be_instance_of(User) end end factory_girl-4.5.0/spec/acceptance/attribute_aliases_spec.rb0000644000004100000410000000174512435642645024341 0ustar www-datawww-datarequire 'spec_helper' describe "attribute aliases" do before do define_model('User', name: :string, age: :integer) define_model('Post', user_id: :integer) do belongs_to :user end FactoryGirl.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 { FactoryGirl.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 { FactoryGirl.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_girl-4.5.0/spec/acceptance/private_attributes_spec.rb0000644000004100000410000000054512435642645024552 0ustar www-datawww-datarequire 'spec_helper' describe 'setting private attributes' do it 'raises a NoMethodError' do define_class('User') do private attr_accessor :foo end FactoryGirl.define do factory :user do foo 123 end end expect do FactoryGirl.build(:user) end.to raise_error NoMethodError, /foo=/ end end factory_girl-4.5.0/spec/acceptance/activesupport_instrumentation_spec.rb0000644000004100000410000000340712435642645027065 0ustar www-datawww-datarequire "spec_helper" unless ActiveSupport::Notifications.respond_to?(:subscribed) module SubscribedBehavior def subscribed(callback, *args, &block) subscriber = subscribe(*args, &callback) yield ensure unsubscribe(subscriber) end end ActiveSupport::Notifications.extend SubscribedBehavior end describe "using ActiveSupport::Instrumentation to track factory interaction" do before do define_model("User", email: :string) FactoryGirl.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_girl.run_factory") do FactoryGirl.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] tracked_invocations[factory_name] ||= {} tracked_invocations[factory_name][strategy_name] ||= 0 tracked_invocations[factory_name][strategy_name] += 1 end ActiveSupport::Notifications.subscribed(callback, "factory_girl.run_factory") do FactoryGirl.build_list(:slow_user, 2) FactoryGirl.build_list(:user, 5) FactoryGirl.create_list(:user, 2) FactoryGirl.attributes_for(:slow_user) end expect(tracked_invocations[:slow_user]).to eq(build: 2, attributes_for: 1) expect(tracked_invocations[:user]).to eq(build: 5, create: 2) end end factory_girl-4.5.0/spec/acceptance/skip_create_spec.rb0000644000004100000410000000057112435642645023122 0ustar www-datawww-datarequire "spec_helper" describe "skipping the default create" do before do define_model("User", email: :string) FactoryGirl.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(FactoryGirl.create(:user)).not_to be_persisted end end factory_girl-4.5.0/spec/acceptance/callbacks_spec.rb0000644000004100000410000001560412435642645022553 0ustar www-datawww-datarequire 'spec_helper' describe "callbacks" do before do define_model("User", first_name: :string, last_name: :string) FactoryGirl.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 = FactoryGirl.build_stubbed(:user_with_callbacks) expect(user.first_name).to eq 'Stubby' end it "runs the after(:build) callback when building" do user = FactoryGirl.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 = FactoryGirl.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 = FactoryGirl.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 = FactoryGirl.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 FactoryGirl.define do factory :user do after :build, &:confirm! end end end it 'runs the callback correctly' do user = FactoryGirl.build(:user) expect(user).to be_confirmed end end describe "callbacks using syntax methods without referencing FactoryGirl explicitly" do before do define_model("User", first_name: :string, last_name: :string) FactoryGirl.define do sequence(:sequence_1) sequence(:sequence_2) sequence(:sequence_3) factory :user do after(:stub) { generate(:sequence_3) } after(:build) { |user| user.first_name = generate(:sequence_1) } after(:create) { |user, evaluator| user.last_name = generate(:sequence_2) } end end end it "works when the callback has no variables" do FactoryGirl.build_stubbed(:user) expect(FactoryGirl.generate(:sequence_3)).to eq 2 end it "works when the callback has one variable" do expect(FactoryGirl.build(:user).first_name).to eq 1 end it "works when the callback has two variables" do expect(FactoryGirl.create(:user).last_name).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 FactoryGirl.register_strategy(:custom_before, custom_before) FactoryGirl.register_strategy(:custom_after, custom_after) FactoryGirl.register_strategy(:totally_custom, totally_custom) FactoryGirl.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(FactoryGirl.build(:user).name).to eq "John Doe" expect(FactoryGirl.custom_before(:user).name).to eq "Overridden First Doe" end it "runs a custom after callback when the proper strategy executes" do expect(FactoryGirl.build(:user).name).to eq "John Doe" expect(FactoryGirl.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(FactoryGirl.build(:user).name).to eq "John Doe" expect(FactoryGirl.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) FactoryGirl.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(FactoryGirl.create(:user, name: 'John Doe').name).to eq 'JOHN DOE' end it 'does not bind the callback to building' do expect(FactoryGirl.build(:user, name: 'John Doe').name).to eq 'John Doe' end it 'binds the callback to stubbing' do expect(FactoryGirl.build_stubbed(:user, name: 'John Doe').name).to eq 'JOHN DOE' end end describe 'global callbacks' do include FactoryGirl::Syntax::Methods before do define_model('User', name: :string) define_model('Company', name: :string) FactoryGirl.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_girl-4.5.0/spec/acceptance/create_pair_spec.rb0000644000004100000410000000132212435642645023102 0ustar www-datawww-datarequire 'spec_helper' describe "create multiple instances" do before do define_model('Post', title: :string, position: :integer) FactoryGirl.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 { FactoryGirl.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_girl-4.5.0/spec/acceptance/modify_factories_spec.rb0000644000004100000410000001062012435642645024153 0ustar www-datawww-datarequire "spec_helper" describe "modifying factories" do include FactoryGirl::Syntax::Methods before do define_model('User', name: :string, admin: :boolean, email: :string, login: :string) FactoryGirl.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 FactoryGirl.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 FactoryGirl.define { factory :user } end.to raise_error(FactoryGirl::DuplicateDefinitionError, "Factory already registered: user") end it "does allow the factory to be subsequently modified" do FactoryGirl.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 FactoryGirl.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 FactoryGirl.define do trait :rockstar do name "Johnny Rockstar!!!" end end FactoryGirl.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 FactoryGirl.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 dynamic attributes" do subject { create(:user, email: "perfect@example.com") } its(:name) { should eq "Great User" } its(:email) { should eq "perfect@example.com" } end context "overriding static attributes" 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 dynamic attributes" 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 static attributes" 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 FactoryGirl.modify do factory :user do admin false end end expect(create(:admin)).to be_admin end it "allows for overriding child classes" do FactoryGirl.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 expect { FactoryGirl.modify do factory :unknown_factory end }.to raise_error(ArgumentError) end end factory_girl-4.5.0/spec/acceptance/definition_spec.rb0000644000004100000410000000060512435642645022757 0ustar www-datawww-datarequire 'spec_helper' describe "an instance generated by a factory with a custom class name" do before do define_model("User", admin: :boolean) FactoryGirl.define do factory :user factory :admin, class: User do admin { true } end end end subject { FactoryGirl.create(:admin) } it { should be_kind_of(User) } it { should be_admin } end factory_girl-4.5.0/spec/factory_girl_spec.rb0000644000004100000410000000123512435642645021225 0ustar www-datawww-datarequire "spec_helper" describe FactoryGirl do let(:factory) { FactoryGirl::Factory.new(:object) } let(:sequence) { FactoryGirl::Sequence.new(:email) } let(:trait) { FactoryGirl::Trait.new(:admin) } it "finds a registered factory" do FactoryGirl.register_factory(factory) expect(FactoryGirl.factory_by_name(factory.name)).to eq factory end it "finds a registered sequence" do FactoryGirl.register_sequence(sequence) expect(FactoryGirl.sequence_by_name(sequence.name)).to eq sequence end it "finds a registered trait" do FactoryGirl.register_trait(trait) expect(FactoryGirl.trait_by_name(trait.name)).to eq trait end end factory_girl-4.5.0/.travis.yml0000644000004100000410000000052212435642645016357 0ustar www-datawww-datarvm: - 1.9.3 - 2.0.0 - 2.1.0 - jruby-19mode before_install: - gem update --system install: "bundle install" script: "bundle exec rake spec:unit spec:acceptance features" jdk: - openjdk6 gemfile: - gemfiles/3.1.gemfile - gemfiles/3.2.gemfile - gemfiles/4.0.gemfile - gemfiles/4.1.gemfile branches: only: - master factory_girl-4.5.0/lib/0000755000004100000410000000000012435642645015015 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/0000755000004100000410000000000012435642645017501 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/declaration_list.rb0000644000004100000410000000173512435642645023354 0ustar www-datawww-datamodule FactoryGirl # @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.inject([]) { |result, declaration| result += declaration.to_attributes } end def overridable? @overridable end end end factory_girl-4.5.0/lib/factory_girl/syntax_runner.rb0000644000004100000410000000013712435642645022746 0ustar www-datawww-datamodule FactoryGirl # @api private class SyntaxRunner include Syntax::Methods end end factory_girl-4.5.0/lib/factory_girl/declaration/0000755000004100000410000000000012435642645021766 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/declaration/dynamic.rb0000644000004100000410000000076212435642645023744 0ustar www-datawww-datamodule FactoryGirl class Declaration # @api private class Dynamic < Declaration def initialize(name, ignored = false, block = nil) super(name, ignored) @block = block end def ==(other) 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_girl-4.5.0/lib/factory_girl/declaration/association.rb0000644000004100000410000000116412435642645024631 0ustar www-datawww-datamodule FactoryGirl 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) name == other.name && options == other.options end protected attr_reader :options private def build factory_name = @overrides[:factory] || name [Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)] end end end end factory_girl-4.5.0/lib/factory_girl/declaration/implicit.rb0000644000004100000410000000136012435642645024125 0ustar www-datawww-datamodule FactoryGirl class Declaration # @api private class Implicit < Declaration def initialize(name, factory = nil, ignored = false) super(name, ignored) @factory = factory end def ==(other) name == other.name && factory == other.factory && ignored == other.ignored end protected attr_reader :factory private def build if FactoryGirl.factories.registered?(name) [Attribute::Association.new(name, name, {})] elsif FactoryGirl.sequences.registered?(name) [Attribute::Sequence.new(name, name, @ignored)] else @factory.inherit_traits([name]) [] end end end end end factory_girl-4.5.0/lib/factory_girl/declaration/static.rb0000644000004100000410000000075212435642645023606 0ustar www-datawww-datamodule FactoryGirl class Declaration # @api private class Static < Declaration def initialize(name, value, ignored = false) super(name, ignored) @value = value end def ==(other) name == other.name && value == other.value && ignored == other.ignored end protected attr_reader :value private def build [Attribute::Static.new(name, @value, @ignored)] end end end end factory_girl-4.5.0/lib/factory_girl/aliases.rb0000644000004100000410000000054012435642645021446 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/configuration.rb0000644000004100000410000000227512435642645022703 0ustar www-datawww-datamodule FactoryGirl # @api private class Configuration attr_reader :factories, :sequences, :traits, :strategies, :callback_names 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 to_create { |instance| instance.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 def duplicate_attribute_assignment_from_initialize_with false end def duplicate_attribute_assignment_from_initialize_with=(value) ActiveSupport::Deprecation.warn 'Assignment of duplicate_attribute_assignment_from_initialize_with is unnecessary as this is now default behavior in FactoryGirl 4.0; this line can be removed', caller end end end factory_girl-4.5.0/lib/factory_girl/null_factory.rb0000644000004100000410000000066612435642645022537 0ustar www-datawww-datamodule FactoryGirl # @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; FactoryGirl::Evaluator; end def hierarchy_class; FactoryGirl::DefinitionHierarchy; end end end factory_girl-4.5.0/lib/factory_girl/evaluator.rb0000644000004100000410000000377012435642645022037 0ustar www-datawww-datarequire 'active_support/core_ext/hash/except' require 'active_support/core_ext/class/attribute' module FactoryGirl # @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) { :create } 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) 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) 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_girl-4.5.0/lib/factory_girl/errors.rb0000644000004100000410000000202012435642645021334 0ustar www-datawww-datamodule FactoryGirl # Raised when a factory is defined that attempts to instantiate itself. class AssociationDefinitionError < 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 invalid attribute: # * Defining an attribute which has a name ending in "=" # * Defining an attribute with both a static and lazy value # * Defining an attribute twice in the same factory class AttributeDefinitionError < 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_girl-4.5.0/lib/factory_girl/definition_hierarchy.rb0000644000004100000410000000172112435642645024215 0ustar www-datawww-datamodule FactoryGirl class DefinitionHierarchy def callbacks FactoryGirl.callbacks end def constructor FactoryGirl.constructor end def to_create FactoryGirl.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_girl-4.5.0/lib/factory_girl/syntax/0000755000004100000410000000000012435642645021027 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/syntax/default.rb0000644000004100000410000000352112435642645023001 0ustar www-datawww-datamodule FactoryGirl 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 = FactoryGirl::DefinitionProxy.new(factory.definition) proxy.instance_eval(&block) if block_given? FactoryGirl.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) FactoryGirl.register_sequence(Sequence.new(name, *args, &block)) end def trait(name, &block) FactoryGirl.register_trait(Trait.new(name, &block)) end def to_create(&block) FactoryGirl.to_create(&block) end def skip_create FactoryGirl.skip_create end def initialize_with(&block) FactoryGirl.initialize_with(&block) end def self.run(block) new.instance_eval(&block) end delegate :before, :after, :callback, to: :configuration private def configuration FactoryGirl.configuration end end class ModifyDSL def factory(name, options = {}, &block) factory = FactoryGirl.factory_by_name(name) proxy = FactoryGirl::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_girl-4.5.0/lib/factory_girl/syntax/methods.rb0000644000004100000410000000733112435642645023023 0ustar www-datawww-datamodule FactoryGirl module Syntax ## This module is a container for all strategy methods provided by ## FactoryGirl. This includes all the default strategies provided ({Methods#build}, ## {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as well as ## the complementary *_list 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 FactoryGirl.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) # (see #strategy_method_list) # @return [Array] array of built objects defined by the factory # @!method create_list(name, amount, *traits_and_overrides) # (see #strategy_method_list) # @return [Array] array of created objects defined by the factory # @!method build_stubbed_list(name, amount, *traits_and_overrides) # (see #strategy_method_list) # @return [Array] array of stubbed objects defined by the factory # @!method attributes_for_list(name, amount, *traits_and_overrides) # (see #strategy_method_list) # @return [Array] array of attribute hashes for the factory # @!method strategy_method # @!visibility private # @param [Symbol] name 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 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 # 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) FactoryGirl.sequence_by_name(name).next end end end end factory_girl-4.5.0/lib/factory_girl/trait.rb0000644000004100000410000000117312435642645021153 0ustar www-datawww-datamodule FactoryGirl # @api private class Trait attr_reader :name, :definition def initialize(name, &block) @name = name @block = block @definition = Definition.new(@name) proxy = FactoryGirl::DefinitionProxy.new(@definition) proxy.instance_eval(&@block) if block_given? 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_girl-4.5.0/lib/factory_girl/evaluator_class_definer.rb0000644000004100000410000000100412435642645024704 0ustar www-datawww-datamodule FactoryGirl # @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_girl-4.5.0/lib/factory_girl/factory.rb0000644000004100000410000000762212435642645021504 0ustar www-datawww-datarequire 'active_support/core_ext/hash/keys' require 'active_support/inflector' module FactoryGirl # @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(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 # # FactoryGirl.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 # # FactoryGirl.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) self.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 FactoryGirl.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_girl-4.5.0/lib/factory_girl/declaration.rb0000644000004100000410000000067612435642645022324 0ustar www-datawww-datarequire 'factory_girl/declaration/static' require 'factory_girl/declaration/dynamic' require 'factory_girl/declaration/association' require 'factory_girl/declaration/implicit' module FactoryGirl # @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_girl-4.5.0/lib/factory_girl/definition_proxy.rb0000644000004100000410000001217512435642645023425 0ustar www-datawww-datamodule FactoryGirl class DefinitionProxy UNPROXIED_METHODS = %w(__send__ __id__ nil? send object_id extend instance_eval initialize block_given? raise caller method) (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 FactoryGirl::MethodDefinitionError, message end # Adds an attribute that should be assigned on generated instances for this # factory. # # This method should be called with either a value or block, but not both. If # called with a block, the attribute will be generated "lazily," whenever an # instance is generated. Lazy attribute blocks will not be called if that # attribute is overridden for a specific instance. # # When defining lazy attributes, an instance of FactoryGirl::Strategy will # be yielded, allowing associations to be built using the correct build # strategy. # # Arguments: # * name: +Symbol+ or +String+ # The name of this attribute. This will be assigned using "name=" for # generated instances. # * value: +Object+ # If no block is given, this value will be used for this attribute. def add_attribute(name, value = nil, &block) raise AttributeDefinitionError, 'Both value and block given' if value && block_given? declaration = if block_given? Declaration::Dynamic.new(name, @ignore, block) else Declaration::Static.new(name, value, @ignore) end @definition.declare_attribute(declaration) end def ignore(&block) ActiveSupport::Deprecation.warn "`#ignore` is deprecated and will be "\ "removed in 5.0. Please use `#transient` instead." transient &block 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_girl will look for a sequence # or association with the same name. This means that: # # factory :user do # email { create(:email) } # association :account # end # # and: # # factory :user do # email # account # end # # are equivalent. def method_missing(name, *args, &block) if args.empty? && block.nil? @definition.declare_attribute(Declaration::Implicit.new(name, @definition, @ignore)) elsif args.first.respond_to?(:has_key?) && args.first.has_key?(:factory) association(name, *args) else add_attribute(name, *args, &block) 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 { FactoryGirl.create(:email) } # end # # Except that no globally available sequence will be defined. def sequence(name, *args, &block) sequence = Sequence.new(name, *args, &block) 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) @definition.declare_attribute(Declaration::Association.new(name, *options)) 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 end end factory_girl-4.5.0/lib/factory_girl/strategy/0000755000004100000410000000000012435642645021343 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/strategy/attributes_for.rb0000644000004100000410000000032112435642645024720 0ustar www-datawww-datamodule FactoryGirl module Strategy class AttributesFor def association(runner) runner.run(:null) end def result(evaluation) evaluation.hash end end end end factory_girl-4.5.0/lib/factory_girl/strategy/stub.rb0000644000004100000410000000414112435642645022645 0ustar www-datawww-datamodule FactoryGirl module Strategy class Stub @@next_id = 1000 def association(runner) runner.run(:build_stubbed) end def result(evaluation) evaluation.object.tap do |instance| stub_database_interaction_on_result(instance) evaluation.notify(:after_stub, instance) end end private def next_id @@next_id += 1 end def stub_database_interaction_on_result(result_instance) result_instance.id ||= next_id result_instance.instance_eval do def persisted? !new_record? end def new_record? id.nil? end def save(*args) raise "stubbed models are not allowed to access the database - #{self.class.to_s}#save(#{args.join(",")})" end def destroy(*args) raise "stubbed models are not allowed to access the database - #{self.class.to_s}#destroy(#{args.join(",")})" end def connection raise "stubbed models are not allowed to access the database - #{self.class.to_s}#connection()" end def reload raise "stubbed models are not allowed to access the database - #{self.class.to_s}#reload()" end def update_attribute(*args) raise "stubbed models are not allowed to access the database - #{self.class.to_s}#update_attribute(#{args.join(",")})" end def update_column(*args) raise "stubbed models are not allowed to access the database - #{self.class.to_s}#update_column(#{args.join(",")})" end end created_at_missing_default = result_instance.respond_to?(:created_at) && !result_instance.created_at result_instance_missing_created_at = !result_instance.respond_to?(:created_at) if created_at_missing_default || result_instance_missing_created_at result_instance.instance_eval do def created_at @created_at ||= Time.now.in_time_zone end end end end end end end factory_girl-4.5.0/lib/factory_girl/strategy/create.rb0000644000004100000410000000065012435642645023134 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/strategy/null.rb0000644000004100000410000000022612435642645022642 0ustar www-datawww-datamodule FactoryGirl module Strategy class Null def association(runner) end def result(evaluation) end end end end factory_girl-4.5.0/lib/factory_girl/strategy/build.rb0000644000004100000410000000042612435642645022771 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/attribute_assigner.rb0000644000004100000410000000526412435642645023733 0ustar www-datawww-datamodule FactoryGirl # @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.inject({}) 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.map do |attribute| override_names.map { |override| attribute.name if attribute.alias_for?(override) && attribute.name != override && !ignored_attribute_names.include?(override) } end.flatten.compact end end end factory_girl-4.5.0/lib/factory_girl/null_object.rb0000644000004100000410000000075112435642645022331 0ustar www-datawww-datamodule FactoryGirl # @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?(*args) false end end end factory_girl-4.5.0/lib/factory_girl/strategy_calculator.rb0000644000004100000410000000072112435642645024101 0ustar www-datawww-datamodule FactoryGirl # @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 FactoryGirl.strategy_by_name(@name_or_object) end end end factory_girl-4.5.0/lib/factory_girl/callback.rb0000644000004100000410000000165312435642645021567 0ustar www-datawww-datamodule FactoryGirl 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 FactoryGirl.callback_names.include?(name) raise InvalidCallbackNameError, "#{name} is not a valid callback name. " + "Valid callback names are #{FactoryGirl.callback_names.inspect}" end end def syntax_runner @syntax_runner ||= SyntaxRunner.new end end end factory_girl-4.5.0/lib/factory_girl/callbacks_observer.rb0000644000004100000410000000070212435642645023653 0ustar www-datawww-datamodule FactoryGirl # @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_girl-4.5.0/lib/factory_girl/reload.rb0000644000004100000410000000023312435642645021272 0ustar www-datawww-datamodule FactoryGirl def self.reload reset_configuration register_default_strategies register_default_callbacks find_definitions end end factory_girl-4.5.0/lib/factory_girl/version.rb0000644000004100000410000000005312435642645021511 0ustar www-datawww-datamodule FactoryGirl VERSION = '4.5.0' end factory_girl-4.5.0/lib/factory_girl/definition.rb0000644000004100000410000000626412435642645022166 0ustar www-datawww-datamodule FactoryGirl # @api private class Definition attr_reader :defined_traits, :declarations def initialize(name = nil, base_traits = []) @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| FactoryGirl.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) || FactoryGirl.trait_by_name(name) end def trait_for(name) defined_traits.detect { |trait| trait.name == name } end def initialize_copy(source) super @attributes = nil @compiled = false end def aggregate_from_traits_and_self(method_name, &block) compile [].tap do |list| base_traits.each do |trait| list << trait.send(method_name) end list << instance_exec(&block) additional_traits.each do |trait| list << trait.send(method_name) end end.flatten.compact end end end factory_girl-4.5.0/lib/factory_girl/linter.rb0000644000004100000410000000174312435642645021330 0ustar www-datawww-datamodule FactoryGirl class Linter def self.lint!(factories_to_lint) new(factories_to_lint).lint! end def initialize(factories_to_lint) @factories_to_lint = factories_to_lint @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 def calculate_invalid_factories factories_to_lint.inject({}) do |result, factory| begin FactoryGirl.create(factory.name) rescue => error result[factory] = error end result end end def error_message lines = invalid_factories.map do |factory, exception| "* #{factory.name} - #{exception.message} (#{exception.class.name})" end <<-ERROR_MESSAGE.strip The following factories are invalid: #{lines.join("\n")} ERROR_MESSAGE end end end factory_girl-4.5.0/lib/factory_girl/evaluation.rb0000644000004100000410000000071712435642645022202 0ustar www-datawww-datarequire 'observer' module FactoryGirl class Evaluation include Observable def initialize(attribute_assigner, to_create) @attribute_assigner = attribute_assigner @to_create = to_create end delegate :object, :hash, to: :@attribute_assigner def create(result_instance) @to_create[result_instance] end def notify(name, result_instance) changed notify_observers(name, result_instance) end end end factory_girl-4.5.0/lib/factory_girl/attribute/0000755000004100000410000000000012435642645021504 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/attribute/dynamic.rb0000644000004100000410000000071412435642645023457 0ustar www-datawww-datamodule FactoryGirl class Attribute # @api private class Dynamic < Attribute def initialize(name, ignored, block) super(name, ignored) @block = block end def to_proc block = @block -> { value = block.arity == 1 ? instance_exec(self, &block) : instance_exec(&block) raise SequenceAbuseError if FactoryGirl::Sequence === value value } end end end end factory_girl-4.5.0/lib/factory_girl/attribute/association.rb0000644000004100000410000000111712435642645024345 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/attribute/sequence.rb0000644000004100000410000000050312435642645023637 0ustar www-datawww-datamodule FactoryGirl class Attribute # @api private class Sequence < Attribute def initialize(name, sequence, ignored) super(name, ignored) @sequence = sequence end def to_proc sequence = @sequence -> { FactoryGirl.generate(sequence) } end end end end factory_girl-4.5.0/lib/factory_girl/attribute/static.rb0000644000004100000410000000043112435642645023316 0ustar www-datawww-datamodule FactoryGirl class Attribute # @api private class Static < Attribute def initialize(name, value, ignored) super(name, ignored) @value = value end def to_proc value = @value -> { value } end end end end factory_girl-4.5.0/lib/factory_girl/decorator/0000755000004100000410000000000012435642645021463 5ustar www-datawww-datafactory_girl-4.5.0/lib/factory_girl/decorator/disallows_duplicates_registry.rb0000644000004100000410000000051512435642645030157 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/decorator/attribute_hash.rb0000644000004100000410000000060012435642645025012 0ustar www-datawww-datamodule FactoryGirl class Decorator class AttributeHash < Decorator def initialize(component, attributes = []) super(component) @attributes = attributes end def attributes @attributes.inject({}) do |result, attribute_name| result[attribute_name] = send(attribute_name) result end end end end end factory_girl-4.5.0/lib/factory_girl/decorator/class_key_hash.rb0000644000004100000410000000075312435642645024775 0ustar www-datawww-datamodule FactoryGirl class Decorator class ClassKeyHash < Decorator def [](key) @component[symbolized_key key] end def []=(key, value) @component[symbolized_key key] = value end def key?(key) @component.key? symbolized_key(key) end private def symbolized_key(key) if key.respond_to?(:to_sym) key.to_sym else key.to_s.underscore.to_sym end end end end end factory_girl-4.5.0/lib/factory_girl/decorator/invocation_tracker.rb0000644000004100000410000000054412435642645025677 0ustar www-datawww-datamodule FactoryGirl class Decorator class InvocationTracker < Decorator def initialize(component) super @invoked_methods = [] end def method_missing(name, *args, &block) @invoked_methods << name super end def __invoked_methods__ @invoked_methods.uniq end end end end factory_girl-4.5.0/lib/factory_girl/decorator/new_constructor.rb0000644000004100000410000000036712435642645025254 0ustar www-datawww-datamodule FactoryGirl 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_girl-4.5.0/lib/factory_girl/registry.rb0000644000004100000410000000114012435642645021672 0ustar www-datawww-datamodule FactoryGirl class Registry include Enumerable attr_reader :name def initialize(name) @name = name @items = Decorator::ClassKeyHash.new({}) end def clear @items.clear end def each(&block) @items.values.uniq.each(&block) end def find(name) if registered?(name) @items[name] else raise ArgumentError, "#{@name} not registered: #{name}" end end alias :[] :find def register(name, item) @items[name] = item end def registered?(name) @items.key?(name) end end end factory_girl-4.5.0/lib/factory_girl/strategy_syntax_method_registrar.rb0000644000004100000410000000237712435642645026731 0ustar www-datawww-datamodule FactoryGirl # @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| amount.times.map { 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| 2.times.map { send(strategy_name, name, *traits_and_overrides, &block) } end end def define_syntax_method(name, &block) FactoryGirl::Syntax::Methods.module_exec do define_method(name, &block) end end end end factory_girl-4.5.0/lib/factory_girl/decorator.rb0000644000004100000410000000060212435642645022006 0ustar www-datawww-datamodule FactoryGirl class Decorator < BasicObject undef_method :== def initialize(component) @component = component end def method_missing(name, *args, &block) @component.send(name, *args, &block) end def send(symbol, *args) __send__(symbol, *args) end def self.const_missing(name) ::Object.const_get(name) end end end factory_girl-4.5.0/lib/factory_girl/factory_runner.rb0000644000004100000410000000132212435642645023064 0ustar www-datawww-datamodule FactoryGirl 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 = FactoryGirl.factory_by_name(@name) factory.compile if @traits.any? factory = factory.with_traits(@traits) end instrumentation_payload = { name: @name, strategy: runner_strategy } ActiveSupport::Notifications.instrument('factory_girl.run_factory', instrumentation_payload) do factory.run(runner_strategy, @overrides, &block) end end end end factory_girl-4.5.0/lib/factory_girl/sequence.rb0000644000004100000410000000206412435642645021640 0ustar www-datawww-datamodule FactoryGirl # Sequences are defined using sequence within a FactoryGirl.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 private def value @value.peek end def increment_value @value.next end class EnumeratorAdapter def initialize(value) @value = value end def peek @value end def next @value = @value.next end end end end factory_girl-4.5.0/lib/factory_girl/attribute_list.rb0000644000004100000410000000302612435642645023065 0ustar www-datawww-datamodule FactoryGirl # @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 raise AssociationDefinitionError, "Self-referencing association '#{attribute.name}' in '#{attribute.factory}'" end end def attribute_defined?(attribute_name) @attributes.any? do |attribute| attribute.name == attribute_name end end end end factory_girl-4.5.0/lib/factory_girl/find_definitions.rb0000644000004100000410000000145112435642645023342 0ustar www-datawww-datamodule FactoryGirl class << self # An Array of strings specifying locations that should be searched for # factory definitions. By default, factory_girl 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_girl-4.5.0/lib/factory_girl/syntax.rb0000644000004100000410000000017212435642645021354 0ustar www-datawww-datarequire 'factory_girl/syntax/methods' require 'factory_girl/syntax/default' module FactoryGirl module Syntax end end factory_girl-4.5.0/lib/factory_girl/attribute.rb0000644000004100000410000000242012435642645022027 0ustar www-datawww-datarequire 'factory_girl/attribute/static' require 'factory_girl/attribute/dynamic' require 'factory_girl/attribute/association' require 'factory_girl/attribute/sequence' module FactoryGirl # @api private class Attribute attr_reader :name, :ignored def initialize(name, ignored) @name = name.to_sym @ignored = ignored ensure_non_attribute_writer! end def to_proc -> { } end def association? false end def alias_for?(attr) FactoryGirl.aliases_for(attr).include?(name) end private def ensure_non_attribute_writer! NonAttributeWriterValidator.new(@name).validate! end class NonAttributeWriterValidator def initialize(method_name) @method_name = method_name.to_s @method_name_setter_match = @method_name.match(/(.*)=$/) end def validate! if method_is_writer? raise AttributeDefinitionError, error_message end end private def method_is_writer? !!@method_name_setter_match end def attribute_name @method_name_setter_match[1] end def error_message "factory_girl uses '#{attribute_name} value' syntax rather than '#{attribute_name} = value'" end end end end factory_girl-4.5.0/lib/factory_girl.rb0000644000004100000410000000755312435642645020040 0ustar www-datawww-datarequire 'set' require 'active_support/core_ext/module/delegation' require 'active_support/deprecation' require 'active_support/notifications' require 'factory_girl/definition_hierarchy' require 'factory_girl/configuration' require 'factory_girl/errors' require 'factory_girl/factory_runner' require 'factory_girl/strategy_syntax_method_registrar' require 'factory_girl/strategy_calculator' require 'factory_girl/strategy/build' require 'factory_girl/strategy/create' require 'factory_girl/strategy/attributes_for' require 'factory_girl/strategy/stub' require 'factory_girl/strategy/null' require 'factory_girl/registry' require 'factory_girl/null_factory' require 'factory_girl/null_object' require 'factory_girl/evaluation' require 'factory_girl/factory' require 'factory_girl/attribute_assigner' require 'factory_girl/evaluator' require 'factory_girl/evaluator_class_definer' require 'factory_girl/attribute' require 'factory_girl/callback' require 'factory_girl/callbacks_observer' require 'factory_girl/declaration_list' require 'factory_girl/declaration' require 'factory_girl/sequence' require 'factory_girl/attribute_list' require 'factory_girl/trait' require 'factory_girl/aliases' require 'factory_girl/definition' require 'factory_girl/definition_proxy' require 'factory_girl/syntax' require 'factory_girl/syntax_runner' require 'factory_girl/find_definitions' require 'factory_girl/reload' require 'factory_girl/decorator' require 'factory_girl/decorator/attribute_hash' require 'factory_girl/decorator/class_key_hash' require 'factory_girl/decorator/disallows_duplicates_registry' require 'factory_girl/decorator/invocation_tracker' require 'factory_girl/decorator/new_constructor' require 'factory_girl/linter' require 'factory_girl/version' module FactoryGirl def self.configuration @configuration ||= Configuration.new end def self.reset_configuration @configuration = nil end def self.lint(factories_to_lint = FactoryGirl.factories) Linter.lint!(factories_to_lint) end class << self delegate :factories, :sequences, :traits, :callbacks, :strategies, :callback_names, :to_create, :skip_create, :initialize_with, :constructor, :duplicate_attribute_assignment_from_initialize_with, :duplicate_attribute_assignment_from_initialize_with=, to: :configuration end def self.register_factory(factory) factory.names.each do |name| factories.register(name, factory) end factory end def self.factory_by_name(name) factories.find(name) end def self.register_sequence(sequence) sequence.names.each do |name| sequences.register(name, sequence) end sequence end def self.sequence_by_name(name) sequences.find(name) end def self.register_trait(trait) trait.names.each do |name| traits.register(name, trait) end trait end def self.trait_by_name(name) traits.find(name) end def self.register_strategy(strategy_name, strategy_class) strategies.register(strategy_name, strategy_class) StrategySyntaxMethodRegistrar.new(strategy_name).define_strategy_methods end def self.strategy_by_name(name) strategies.find(name) end def self.register_default_strategies register_strategy(:build, FactoryGirl::Strategy::Build) register_strategy(:create, FactoryGirl::Strategy::Create) register_strategy(:attributes_for, FactoryGirl::Strategy::AttributesFor) register_strategy(:build_stubbed, FactoryGirl::Strategy::Stub) register_strategy(:null, FactoryGirl::Strategy::Null) end def self.register_default_callbacks register_callback(:after_build) register_callback(:after_create) register_callback(:after_stub) register_callback(:before_create) end def self.register_callback(name) name = name.to_sym callback_names << name end end FactoryGirl.register_default_strategies FactoryGirl.register_default_callbacks factory_girl-4.5.0/gemfiles/0000755000004100000410000000000012435642645016042 5ustar www-datawww-datafactory_girl-4.5.0/gemfiles/4.0.gemfile0000644000004100000410000000017612435642645017701 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord", "~> 4.0.1" gemspec :path => "../" factory_girl-4.5.0/gemfiles/3.1.gemfile0000644000004100000410000000017712435642645017702 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord", "~> 3.1.12" gemspec :path => "../" factory_girl-4.5.0/gemfiles/3.1.gemfile.lock0000644000004100000410000000354312435642645020631 0ustar www-datawww-dataPATH remote: ../ specs: factory_girl (4.5.0) activesupport (>= 3.0.0) GEM remote: https://rubygems.org/ specs: activemodel (3.1.12) activesupport (= 3.1.12) builder (~> 3.0.0) i18n (~> 0.6) activerecord (3.1.12) activemodel (= 3.1.12) activesupport (= 3.1.12) arel (~> 2.2.3) tzinfo (~> 0.3.29) activesupport (3.1.12) multi_json (~> 1.0) appraisal (1.0.0) bundler rake thor (>= 0.14.0) arel (2.2.3) aruba (0.5.3) childprocess (>= 0.3.6) cucumber (>= 1.1.1) rspec-expectations (>= 2.7.0) bourne (1.5.0) mocha (>= 0.13.2, < 0.15) builder (3.0.4) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.3.15) builder (>= 2.1.2) diff-lcs (>= 1.1.3) gherkin (~> 2.12) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.1) diff-lcs (1.1.3) docile (1.1.3) ffi (1.9.3) ffi (1.9.3-java) gherkin (2.12.2) multi_json (~> 1.3) gherkin (2.12.2-java) multi_json (~> 1.3) i18n (0.6.9) metaclass (0.0.4) mocha (0.14.0) metaclass (~> 0.0.1) multi_json (1.10.1) multi_test (0.1.1) rake (10.3.2) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.2) rspec-expectations (2.12.1) diff-lcs (~> 1.1.3) rspec-mocks (2.12.2) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) sqlite3 (1.3.8) thor (0.19.1) timecop (0.7.1) tzinfo (0.3.39) yard (0.8.7.3) PLATFORMS java ruby DEPENDENCIES activerecord (~> 3.1.12) appraisal (~> 1.0.0) aruba bourne cucumber (~> 1.3.15) factory_girl! mocha (>= 0.12.8) rspec (~> 2.12.0) simplecov sqlite3 timecop yard factory_girl-4.5.0/gemfiles/3.2.gemfile.lock0000644000004100000410000000355512435642645020635 0ustar www-datawww-dataPATH remote: ../ specs: factory_girl (4.5.0) activesupport (>= 3.0.0) GEM remote: https://rubygems.org/ specs: activemodel (3.2.15) activesupport (= 3.2.15) builder (~> 3.0.0) activerecord (3.2.15) activemodel (= 3.2.15) activesupport (= 3.2.15) arel (~> 3.0.2) tzinfo (~> 0.3.29) activesupport (3.2.15) i18n (~> 0.6, >= 0.6.4) multi_json (~> 1.0) appraisal (1.0.0) bundler rake thor (>= 0.14.0) arel (3.0.2) aruba (0.5.3) childprocess (>= 0.3.6) cucumber (>= 1.1.1) rspec-expectations (>= 2.7.0) bourne (1.5.0) mocha (>= 0.13.2, < 0.15) builder (3.0.4) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.3.15) builder (>= 2.1.2) diff-lcs (>= 1.1.3) gherkin (~> 2.12) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.1) diff-lcs (1.1.3) docile (1.1.3) ffi (1.9.3) ffi (1.9.3-java) gherkin (2.12.2) multi_json (~> 1.3) gherkin (2.12.2-java) multi_json (~> 1.3) i18n (0.6.9) metaclass (0.0.4) mocha (0.14.0) metaclass (~> 0.0.1) multi_json (1.10.1) multi_test (0.1.1) rake (10.3.2) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.2) rspec-expectations (2.12.1) diff-lcs (~> 1.1.3) rspec-mocks (2.12.2) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) sqlite3 (1.3.8) thor (0.19.1) timecop (0.7.1) tzinfo (0.3.39) yard (0.8.7.3) PLATFORMS java ruby DEPENDENCIES activerecord (~> 3.2.15) appraisal (~> 1.0.0) aruba bourne cucumber (~> 1.3.15) factory_girl! mocha (>= 0.12.8) rspec (~> 2.12.0) simplecov sqlite3 timecop yard factory_girl-4.5.0/gemfiles/4.1.gemfile0000644000004100000410000000017612435642645017702 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord", "~> 4.1.1" gemspec :path => "../" factory_girl-4.5.0/gemfiles/4.0.gemfile.lock0000644000004100000410000000410012435642645020617 0ustar www-datawww-dataPATH remote: ../ specs: factory_girl (4.5.0) activesupport (>= 3.0.0) GEM remote: https://rubygems.org/ specs: activemodel (4.0.5) activesupport (= 4.0.5) builder (~> 3.1.0) activerecord (4.0.5) activemodel (= 4.0.5) activerecord-deprecated_finders (~> 1.0.2) activesupport (= 4.0.5) arel (~> 4.0.0) activerecord-deprecated_finders (1.0.3) activesupport (4.0.5) i18n (~> 0.6, >= 0.6.9) minitest (~> 4.2) multi_json (~> 1.3) thread_safe (~> 0.1) tzinfo (~> 0.3.37) appraisal (1.0.0) bundler rake thor (>= 0.14.0) arel (4.0.2) aruba (0.5.3) childprocess (>= 0.3.6) cucumber (>= 1.1.1) rspec-expectations (>= 2.7.0) bourne (1.5.0) mocha (>= 0.13.2, < 0.15) builder (3.1.4) childprocess (0.3.9) ffi (~> 1.0, >= 1.0.11) cucumber (1.3.15) builder (>= 2.1.2) diff-lcs (>= 1.1.3) gherkin (~> 2.12) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.1) diff-lcs (1.1.3) docile (1.1.3) ffi (1.9.3) ffi (1.9.3-java) gherkin (2.12.2) multi_json (~> 1.3) gherkin (2.12.2-java) multi_json (~> 1.3) i18n (0.6.9) metaclass (0.0.4) minitest (4.7.5) mocha (0.14.0) metaclass (~> 0.0.1) multi_json (1.10.1) multi_test (0.1.1) rake (10.3.2) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.2) rspec-expectations (2.12.1) diff-lcs (~> 1.1.3) rspec-mocks (2.12.2) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) sqlite3 (1.3.8) thor (0.19.1) thread_safe (0.3.4) thread_safe (0.3.4-java) timecop (0.7.1) tzinfo (0.3.39) yard (0.8.7.3) PLATFORMS java ruby DEPENDENCIES activerecord (~> 4.0.1) appraisal (~> 1.0.0) aruba bourne cucumber (~> 1.3.15) factory_girl! mocha (>= 0.12.8) rspec (~> 2.12.0) simplecov sqlite3 timecop yard factory_girl-4.5.0/gemfiles/3.2.gemfile0000644000004100000410000000017712435642645017703 0ustar www-datawww-data# This file was generated by Appraisal source "https://rubygems.org" gem "activerecord", "~> 3.2.15" gemspec :path => "../" factory_girl-4.5.0/gemfiles/4.1.gemfile.lock0000644000004100000410000000365712435642645020640 0ustar www-datawww-dataPATH remote: ../ specs: factory_girl (4.5.0) activesupport (>= 3.0.0) GEM remote: https://rubygems.org/ specs: activemodel (4.1.1) activesupport (= 4.1.1) builder (~> 3.1) activerecord (4.1.1) activemodel (= 4.1.1) activesupport (= 4.1.1) arel (~> 5.0.0) activesupport (4.1.1) i18n (~> 0.6, >= 0.6.9) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.1) tzinfo (~> 1.1) appraisal (1.0.0) bundler rake thor (>= 0.14.0) arel (5.0.1.20140414130214) aruba (0.5.4) childprocess (>= 0.3.6) cucumber (>= 1.1.1) rspec-expectations (>= 2.7.0) bourne (1.5.0) mocha (>= 0.13.2, < 0.15) builder (3.2.2) childprocess (0.5.3) ffi (~> 1.0, >= 1.0.11) cucumber (1.3.15) builder (>= 2.1.2) diff-lcs (>= 1.1.3) gherkin (~> 2.12) multi_json (>= 1.7.5, < 2.0) multi_test (>= 0.1.1) diff-lcs (1.1.3) docile (1.1.3) ffi (1.9.3) gherkin (2.12.2) multi_json (~> 1.3) i18n (0.6.9) json (1.8.1) metaclass (0.0.4) minitest (5.3.4) mocha (0.14.0) metaclass (~> 0.0.1) multi_json (1.10.1) multi_test (0.1.1) rake (10.3.2) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.2) rspec-expectations (2.12.1) diff-lcs (~> 1.1.3) rspec-mocks (2.12.2) simplecov (0.8.2) docile (~> 1.1.0) multi_json simplecov-html (~> 0.8.0) simplecov-html (0.8.0) sqlite3 (1.3.9) thor (0.19.1) thread_safe (0.3.4) timecop (0.7.1) tzinfo (1.2.0) thread_safe (~> 0.1) yard (0.8.7.4) PLATFORMS ruby DEPENDENCIES activerecord (~> 4.1.1) appraisal (~> 1.0.0) aruba bourne cucumber (~> 1.3.15) factory_girl! mocha (>= 0.12.8) rspec (~> 2.12.0) simplecov sqlite3 timecop yard factory_girl-4.5.0/cucumber.yml0000644000004100000410000000003612435642645016576 0ustar www-datawww-datadefault: -r features features factory_girl-4.5.0/metadata.yml0000644000004100000410000003441312435642645016557 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: factory_girl version: !ruby/object:Gem::Version version: 4.5.0 platform: ruby authors: - Josh Clayton - Joe Ferris autorequire: bindir: bin cert_chain: [] date: 2014-10-17 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: activesupport requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.0.0 type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.0.0 - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 2.12.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 2.12.0 - !ruby/object:Gem::Dependency name: cucumber requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.3.15 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.3.15 - !ruby/object:Gem::Dependency name: timecop requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: simplecov requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: aruba requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: mocha requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.12.8 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 0.12.8 - !ruby/object:Gem::Dependency name: bourne requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: appraisal requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.0.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.0.0 - !ruby/object:Gem::Dependency name: activerecord requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.0.0 type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.0.0 - !ruby/object:Gem::Dependency name: sqlite3 requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: yard requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' description: |- factory_girl provides a framework and DSL for defining and using factories - less error-prone, more explicit, and all-around easier to work with than fixtures. email: - jclayton@thoughtbot.com - jferris@thoughtbot.com executables: [] extensions: [] extra_rdoc_files: [] files: - ".autotest" - ".gitignore" - ".rspec" - ".simplecov" - ".travis.yml" - ".yardopts" - Appraisals - CONTRIBUTING.md - GETTING_STARTED.md - Gemfile - Gemfile.lock - LICENSE - NEWS - README.md - Rakefile - cucumber.yml - factory_girl.gemspec - features/find_definitions.feature - features/step_definitions/database_steps.rb - features/step_definitions/factory_girl_steps.rb - features/support/env.rb - features/support/factories.rb - gemfiles/3.1.gemfile - gemfiles/3.1.gemfile.lock - gemfiles/3.2.gemfile - gemfiles/3.2.gemfile.lock - gemfiles/4.0.gemfile - gemfiles/4.0.gemfile.lock - gemfiles/4.1.gemfile - gemfiles/4.1.gemfile.lock - lib/factory_girl.rb - lib/factory_girl/aliases.rb - lib/factory_girl/attribute.rb - lib/factory_girl/attribute/association.rb - lib/factory_girl/attribute/dynamic.rb - lib/factory_girl/attribute/sequence.rb - lib/factory_girl/attribute/static.rb - lib/factory_girl/attribute_assigner.rb - lib/factory_girl/attribute_list.rb - lib/factory_girl/callback.rb - lib/factory_girl/callbacks_observer.rb - lib/factory_girl/configuration.rb - lib/factory_girl/declaration.rb - lib/factory_girl/declaration/association.rb - lib/factory_girl/declaration/dynamic.rb - lib/factory_girl/declaration/implicit.rb - lib/factory_girl/declaration/static.rb - lib/factory_girl/declaration_list.rb - lib/factory_girl/decorator.rb - lib/factory_girl/decorator/attribute_hash.rb - lib/factory_girl/decorator/class_key_hash.rb - lib/factory_girl/decorator/disallows_duplicates_registry.rb - lib/factory_girl/decorator/invocation_tracker.rb - lib/factory_girl/decorator/new_constructor.rb - lib/factory_girl/definition.rb - lib/factory_girl/definition_hierarchy.rb - lib/factory_girl/definition_proxy.rb - lib/factory_girl/errors.rb - lib/factory_girl/evaluation.rb - lib/factory_girl/evaluator.rb - lib/factory_girl/evaluator_class_definer.rb - lib/factory_girl/factory.rb - lib/factory_girl/factory_runner.rb - lib/factory_girl/find_definitions.rb - lib/factory_girl/linter.rb - lib/factory_girl/null_factory.rb - lib/factory_girl/null_object.rb - lib/factory_girl/registry.rb - lib/factory_girl/reload.rb - lib/factory_girl/sequence.rb - lib/factory_girl/strategy/attributes_for.rb - lib/factory_girl/strategy/build.rb - lib/factory_girl/strategy/create.rb - lib/factory_girl/strategy/null.rb - lib/factory_girl/strategy/stub.rb - lib/factory_girl/strategy_calculator.rb - lib/factory_girl/strategy_syntax_method_registrar.rb - lib/factory_girl/syntax.rb - lib/factory_girl/syntax/default.rb - lib/factory_girl/syntax/methods.rb - lib/factory_girl/syntax_runner.rb - lib/factory_girl/trait.rb - lib/factory_girl/version.rb - spec/acceptance/activesupport_instrumentation_spec.rb - spec/acceptance/aliases_spec.rb - spec/acceptance/attribute_aliases_spec.rb - spec/acceptance/attribute_existing_on_object_spec.rb - spec/acceptance/attributes_for_spec.rb - spec/acceptance/attributes_from_instance_spec.rb - spec/acceptance/attributes_ordered_spec.rb - spec/acceptance/build_list_spec.rb - spec/acceptance/build_spec.rb - spec/acceptance/build_stubbed_spec.rb - spec/acceptance/callbacks_spec.rb - spec/acceptance/create_list_spec.rb - spec/acceptance/create_pair_spec.rb - spec/acceptance/create_spec.rb - spec/acceptance/define_child_before_parent_spec.rb - spec/acceptance/defining_methods_inside_a_factory_spec.rb - spec/acceptance/definition_camel_string_spec.rb - spec/acceptance/definition_spec.rb - spec/acceptance/definition_without_block_spec.rb - spec/acceptance/global_initialize_with_spec.rb - spec/acceptance/global_to_create_spec.rb - spec/acceptance/initialize_with_spec.rb - spec/acceptance/keyed_by_class_spec.rb - spec/acceptance/lint_spec.rb - spec/acceptance/modify_factories_spec.rb - spec/acceptance/modify_inherited_spec.rb - spec/acceptance/nested_attributes_spec.rb - spec/acceptance/overrides_spec.rb - spec/acceptance/parent_spec.rb - spec/acceptance/private_attributes_spec.rb - spec/acceptance/register_strategies_spec.rb - spec/acceptance/sequence_context_spec.rb - spec/acceptance/sequence_spec.rb - spec/acceptance/skip_create_spec.rb - spec/acceptance/stub_spec.rb - spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb - spec/acceptance/traits_spec.rb - spec/acceptance/transient_attributes_spec.rb - spec/factory_girl/aliases_spec.rb - spec/factory_girl/attribute/association_spec.rb - spec/factory_girl/attribute/dynamic_spec.rb - spec/factory_girl/attribute/sequence_spec.rb - spec/factory_girl/attribute/static_spec.rb - spec/factory_girl/attribute_list_spec.rb - spec/factory_girl/attribute_spec.rb - spec/factory_girl/callback_spec.rb - spec/factory_girl/declaration/implicit_spec.rb - spec/factory_girl/declaration_list_spec.rb - spec/factory_girl/definition_proxy_spec.rb - spec/factory_girl/definition_spec.rb - spec/factory_girl/disallows_duplicates_registry_spec.rb - spec/factory_girl/evaluator_class_definer_spec.rb - spec/factory_girl/factory_spec.rb - spec/factory_girl/find_definitions_spec.rb - spec/factory_girl/null_factory_spec.rb - spec/factory_girl/null_object_spec.rb - spec/factory_girl/registry_spec.rb - spec/factory_girl/sequence_spec.rb - spec/factory_girl/strategy/attributes_for_spec.rb - spec/factory_girl/strategy/build_spec.rb - spec/factory_girl/strategy/create_spec.rb - spec/factory_girl/strategy/stub_spec.rb - spec/factory_girl/strategy_calculator_spec.rb - spec/factory_girl_spec.rb - spec/spec_helper.rb - spec/support/macros/define_constant.rb - spec/support/matchers/callback.rb - spec/support/matchers/declaration.rb - spec/support/matchers/delegate.rb - spec/support/matchers/trait.rb - spec/support/shared_examples/strategy.rb homepage: https://github.com/thoughtbot/factory_girl licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.9.2 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.2.2 signing_key: specification_version: 4 summary: factory_girl provides a framework and DSL for defining and using model instance factories. test_files: - Appraisals - features/find_definitions.feature - features/step_definitions/database_steps.rb - features/step_definitions/factory_girl_steps.rb - features/support/env.rb - features/support/factories.rb - gemfiles/3.1.gemfile - gemfiles/3.1.gemfile.lock - gemfiles/3.2.gemfile - gemfiles/3.2.gemfile.lock - gemfiles/4.0.gemfile - gemfiles/4.0.gemfile.lock - gemfiles/4.1.gemfile - gemfiles/4.1.gemfile.lock - spec/acceptance/activesupport_instrumentation_spec.rb - spec/acceptance/aliases_spec.rb - spec/acceptance/attribute_aliases_spec.rb - spec/acceptance/attribute_existing_on_object_spec.rb - spec/acceptance/attributes_for_spec.rb - spec/acceptance/attributes_from_instance_spec.rb - spec/acceptance/attributes_ordered_spec.rb - spec/acceptance/build_list_spec.rb - spec/acceptance/build_spec.rb - spec/acceptance/build_stubbed_spec.rb - spec/acceptance/callbacks_spec.rb - spec/acceptance/create_list_spec.rb - spec/acceptance/create_pair_spec.rb - spec/acceptance/create_spec.rb - spec/acceptance/define_child_before_parent_spec.rb - spec/acceptance/defining_methods_inside_a_factory_spec.rb - spec/acceptance/definition_camel_string_spec.rb - spec/acceptance/definition_spec.rb - spec/acceptance/definition_without_block_spec.rb - spec/acceptance/global_initialize_with_spec.rb - spec/acceptance/global_to_create_spec.rb - spec/acceptance/initialize_with_spec.rb - spec/acceptance/keyed_by_class_spec.rb - spec/acceptance/lint_spec.rb - spec/acceptance/modify_factories_spec.rb - spec/acceptance/modify_inherited_spec.rb - spec/acceptance/nested_attributes_spec.rb - spec/acceptance/overrides_spec.rb - spec/acceptance/parent_spec.rb - spec/acceptance/private_attributes_spec.rb - spec/acceptance/register_strategies_spec.rb - spec/acceptance/sequence_context_spec.rb - spec/acceptance/sequence_spec.rb - spec/acceptance/skip_create_spec.rb - spec/acceptance/stub_spec.rb - spec/acceptance/syntax_methods_within_dynamic_attributes_spec.rb - spec/acceptance/traits_spec.rb - spec/acceptance/transient_attributes_spec.rb - spec/factory_girl/aliases_spec.rb - spec/factory_girl/attribute/association_spec.rb - spec/factory_girl/attribute/dynamic_spec.rb - spec/factory_girl/attribute/sequence_spec.rb - spec/factory_girl/attribute/static_spec.rb - spec/factory_girl/attribute_list_spec.rb - spec/factory_girl/attribute_spec.rb - spec/factory_girl/callback_spec.rb - spec/factory_girl/declaration/implicit_spec.rb - spec/factory_girl/declaration_list_spec.rb - spec/factory_girl/definition_proxy_spec.rb - spec/factory_girl/definition_spec.rb - spec/factory_girl/disallows_duplicates_registry_spec.rb - spec/factory_girl/evaluator_class_definer_spec.rb - spec/factory_girl/factory_spec.rb - spec/factory_girl/find_definitions_spec.rb - spec/factory_girl/null_factory_spec.rb - spec/factory_girl/null_object_spec.rb - spec/factory_girl/registry_spec.rb - spec/factory_girl/sequence_spec.rb - spec/factory_girl/strategy/attributes_for_spec.rb - spec/factory_girl/strategy/build_spec.rb - spec/factory_girl/strategy/create_spec.rb - spec/factory_girl/strategy/stub_spec.rb - spec/factory_girl/strategy_calculator_spec.rb - spec/factory_girl_spec.rb - spec/spec_helper.rb - spec/support/macros/define_constant.rb - spec/support/matchers/callback.rb - spec/support/matchers/declaration.rb - spec/support/matchers/delegate.rb - spec/support/matchers/trait.rb - spec/support/shared_examples/strategy.rb has_rdoc: factory_girl-4.5.0/.gitignore0000644000004100000410000000010612435642645016234 0ustar www-datawww-data*.swp test.db factory_girl-*.gem doc .yardoc coverage .bundle tmp bin factory_girl-4.5.0/.yardopts0000644000004100000410000000007112435642645016113 0ustar www-datawww-datalib/**/*.rb - GETTING_STARTED.md CONTRIBUTING.md LICENSE factory_girl-4.5.0/CONTRIBUTING.md0000644000004100000410000000043412435642645016501 0ustar www-datawww-dataContributing to factory\_girl: 1. Fork the [official repository](https://github.com/thoughtbot/factory_girl/tree/master). 2. Make your changes in a topic branch. 3. Send a pull request. Notes: * Contributions without tests won't be accepted. * Please don't update the Gem version. factory_girl-4.5.0/LICENSE0000644000004100000410000000207012435642645015253 0ustar www-datawww-dataCopyright (c) 2008-2014 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_girl-4.5.0/Appraisals0000644000004100000410000000034112435642645016267 0ustar www-datawww-dataappraise "3.1" do gem "activerecord", "~> 3.1.12" end appraise "3.2" do gem "activerecord", "~> 3.2.15" end appraise '4.0' do gem 'activerecord', "~> 4.0.1" end appraise '4.1' do gem 'activerecord', "~> 4.1.1" end factory_girl-4.5.0/README.md0000644000004100000410000000535612435642645015537 0ustar www-datawww-data# factory_girl [![Build Status](https://secure.travis-ci.org/thoughtbot/factory_girl.png)](http://travis-ci.org/thoughtbot/factory_girl?branch=master) [![Dependency Status](https://gemnasium.com/thoughtbot/factory_girl.png)](https://gemnasium.com/thoughtbot/factory_girl) [![Code Climate](https://codeclimate.com/github/thoughtbot/factory_girl.png)](https://codeclimate.com/github/thoughtbot/factory_girl) factory_girl 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_girl with Rails, see [factory_girl_rails](https://github.com/thoughtbot/factory_girl_rails). Documentation ------------- You should find the documentation for your version of factory_girl on [Rubygems](https://rubygems.org/gems/factory_girl). See [GETTING_STARTED] for information on defining and using factories. Install -------- ```shell gem install factory_girl ``` or add the following line to Gemfile: ```ruby gem 'factory_girl' ``` and run `bundle install` from your shell. Supported Ruby versions ----------------------- The factory_girl 3.x+ series supports MRI Ruby 1.9. Additionally, factory_girl 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_girl 2.x. More Information ---------------- * [Rubygems](https://rubygems.org/gems/factory_girl) * [Stack Overflow](http://stackoverflow.com/questions/tagged/factory-girl) * [Issues](https://github.com/thoughtbot/factory_girl/issues) * [GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS](http://robots.thoughtbot.com/) [GETTING_STARTED]: http://rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md Contributing ------------ Please see [CONTRIBUTING.md](https://github.com/thoughtbot/factory_girl/blob/master/CONTRIBUTING.md). Credits ------- factory_girl 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_girl/graphs/contributors). ![thoughtbot](http://thoughtbot.com/assets/tm/logo.png) factory_girl is maintained and funded by [thoughtbot, inc](http://thoughtbot.com/community) The names and logos for thoughtbot are trademarks of thoughtbot, inc. License ------- factory_girl is Copyright © 2008-2014 Joe Ferris and thoughtbot. It is free software, and may be redistributed under the terms specified in the [LICENSE](https://github.com/thoughtbot/factory_girl/blob/master/LICENSE) file. factory_girl-4.5.0/.simplecov0000644000004100000410000000010212435642645016242 0ustar www-datawww-dataSimpleCov.start do add_filter "/spec/" add_filter "/tmp/" end