Run standardrb

This commit applies the changes from running `standardrb --fix`
This commit is contained in:
Daniel Colson 2020-06-05 15:15:18 -04:00
parent 0c75dc27cd
commit 5f1a1de114
75 changed files with 459 additions and 451 deletions

View File

@ -8,7 +8,7 @@ require "cucumber/rake/task"
Bundler::GemHelper.install_tasks(name: "factory_bot") Bundler::GemHelper.install_tasks(name: "factory_bot")
desc "Default: run the specs and features." desc "Default: run the specs and features."
task default: %w(spec:unit spec:acceptance features) task default: %w[spec:unit spec:acceptance features]
namespace :spec do namespace :spec do
desc "Run unit specs" desc "Run unit specs"

View File

@ -2,9 +2,9 @@ $LOAD_PATH << File.expand_path("lib", __dir__)
require "factory_bot/version" require "factory_bot/version"
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "factory_bot" s.name = "factory_bot"
s.version = FactoryBot::VERSION s.version = FactoryBot::VERSION
s.summary = "factory_bot provides a framework and DSL for defining and "\ s.summary = "factory_bot provides a framework and DSL for defining and "\
"using model instance factories." "using model instance factories."
s.description = "factory_bot provides a framework and DSL for defining and "\ s.description = "factory_bot provides a framework and DSL for defining and "\
"using factories - less error-prone, more explicit, and "\ "using factories - less error-prone, more explicit, and "\
@ -18,7 +18,7 @@ Gem::Specification.new do |s|
s.required_ruby_version = Gem::Requirement.new(">= 2.5.0") s.required_ruby_version = Gem::Requirement.new(">= 2.5.0")
s.authors = ["Josh Clayton", "Joe Ferris"] s.authors = ["Josh Clayton", "Joe Ferris"]
s.email = ["jclayton@thoughtbot.com", "jferris@thoughtbot.com"] s.email = ["jclayton@thoughtbot.com", "jferris@thoughtbot.com"]
s.homepage = "https://github.com/thoughtbot/factory_bot" s.homepage = "https://github.com/thoughtbot/factory_bot"
s.metadata["changelog_uri"] = "https://github.com/thoughtbot/factory_bot/blob/master/NEWS.md" s.metadata["changelog_uri"] = "https://github.com/thoughtbot/factory_bot/blob/master/NEWS.md"

View File

@ -1,4 +1,4 @@
Then /^I should find the following for the last category:$/ do |table| Then(/^I should find the following for the last category:$/) do |table|
table.hashes.first.each do |key, value| table.hashes.first.each do |key, value|
expect(Category.last.attributes[key].to_s).to eq value expect(Category.last.attributes[key].to_s).to eq value
end end

View File

@ -7,30 +7,30 @@ end
World(FactoryBotDefinitionsHelper) World(FactoryBotDefinitionsHelper)
When /^"([^"]*)" is added to FactoryBot's file definitions path$/ do |file_name| When(/^"([^"]*)" is added to FactoryBot's file definitions path$/) do |file_name|
new_factory_file = File.join(expand_path("."), file_name.gsub(".rb", "")) new_factory_file = File.join(expand_path("."), file_name.gsub(".rb", ""))
append_file_to_factory_bot_definitions_path(new_factory_file) append_file_to_factory_bot_definitions_path(new_factory_file)
step %{I find definitions} step %(I find definitions)
end end
When /^"([^"]*)" is added to FactoryBot's file definitions path as an absolute path$/ do |file_name| When(/^"([^"]*)" is added to FactoryBot's file definitions path as an absolute path$/) do |file_name|
new_factory_file = File.expand_path(File.join(expand_path("."), file_name.gsub(".rb", ""))) new_factory_file = File.expand_path(File.join(expand_path("."), file_name.gsub(".rb", "")))
append_file_to_factory_bot_definitions_path(new_factory_file) append_file_to_factory_bot_definitions_path(new_factory_file)
step %{I find definitions} step %(I find definitions)
end end
When /^I create a "([^"]*)" instance from FactoryBot$/ do |factory_name| When(/^I create a "([^"]*)" instance from FactoryBot$/) do |factory_name|
FactoryBot.create(factory_name) FactoryBot.create(factory_name)
end end
When /^I find definitions$/ do When(/^I find definitions$/) do
FactoryBot.find_definitions FactoryBot.find_definitions
end end
When /^I reload factories$/ do When(/^I reload factories$/) do
FactoryBot.reload FactoryBot.reload
end end

View File

@ -1,6 +1,6 @@
ActiveRecord::Base.establish_connection( ActiveRecord::Base.establish_connection(
adapter: "sqlite3", adapter: "sqlite3",
database: ":memory:", database: ":memory:"
) )
class CreateSchema < ActiveRecord::Migration[5.0] class CreateSchema < ActiveRecord::Migration[5.0]

View File

@ -81,10 +81,10 @@ module FactoryBot
class << self class << self
delegate :factories, delegate :factories,
:register_strategy, :register_strategy,
:rewind_sequences, :rewind_sequences,
:strategy_by_name, :strategy_by_name,
to: Internal to: Internal
end end
end end

View File

@ -5,14 +5,14 @@ module FactoryBot
self.aliases = [ self.aliases = [
[/(.+)_id/, '\1'], [/(.+)_id/, '\1'],
[/(.*)/, '\1_id'], [/(.*)/, '\1_id']
] ]
def self.aliases_for(attribute) def self.aliases_for(attribute)
aliases.map do |(pattern, replace)| aliases.map { |(pattern, replace)|
if pattern.match(attribute.to_s) if pattern.match(attribute.to_s)
attribute.to_s.sub(pattern, replace).to_sym attribute.to_s.sub(pattern, replace).to_sym
end end
end.compact << attribute }.compact << attribute
end end
end end

View File

@ -6,12 +6,12 @@ module FactoryBot
def initialize(name, factory, overrides) def initialize(name, factory, overrides)
super(name, false) super(name, false)
@factory = factory @factory = factory
@overrides = overrides @overrides = overrides
end end
def to_proc def to_proc
factory = @factory factory = @factory
overrides = @overrides overrides = @overrides
traits_and_overrides = [factory, overrides].flatten traits_and_overrides = [factory, overrides].flatten
factory_name = traits_and_overrides.shift factory_name = traits_and_overrides.shift

View File

@ -14,7 +14,7 @@ module FactoryBot
value = case block.arity value = case block.arity
when 1, -1 then instance_exec(self, &block) when 1, -1 then instance_exec(self, &block)
else instance_exec(&block) else instance_exec(&block)
end end
raise SequenceAbuseError if FactoryBot::Sequence === value raise SequenceAbuseError if FactoryBot::Sequence === value
value value

View File

@ -2,10 +2,10 @@ module FactoryBot
# @api private # @api private
class AttributeAssigner class AttributeAssigner
def initialize(evaluator, build_class, &instance_builder) def initialize(evaluator, build_class, &instance_builder)
@build_class = build_class @build_class = build_class
@instance_builder = instance_builder @instance_builder = instance_builder
@evaluator = evaluator @evaluator = evaluator
@attribute_list = evaluator.class.attribute_list @attribute_list = evaluator.class.attribute_list
@attribute_names_assigned = [] @attribute_names_assigned = []
end end
@ -22,9 +22,8 @@ module FactoryBot
def hash def hash
@evaluator.instance = build_hash @evaluator.instance = build_hash
attributes_to_set_on_hash.reduce({}) do |result, attribute| attributes_to_set_on_hash.each_with_object({}) do |attribute, result|
result[attribute] = get(attribute) result[attribute] = get(attribute)
result
end end
end end
@ -33,13 +32,13 @@ module FactoryBot
def method_tracking_evaluator def method_tracking_evaluator
@method_tracking_evaluator ||= Decorator::AttributeHash.new( @method_tracking_evaluator ||= Decorator::AttributeHash.new(
decorated_evaluator, decorated_evaluator,
attribute_names_to_assign, attribute_names_to_assign
) )
end end
def decorated_evaluator def decorated_evaluator
Decorator::InvocationTracker.new( Decorator::InvocationTracker.new(
Decorator::NewConstructor.new(@evaluator, @build_class), Decorator::NewConstructor.new(@evaluator, @build_class)
) )
end end
@ -96,11 +95,11 @@ module FactoryBot
end end
def alias_names_to_ignore def alias_names_to_ignore
@attribute_list.non_ignored.flat_map do |attribute| @attribute_list.non_ignored.flat_map { |attribute|
override_names.map do |override| override_names.map do |override|
attribute.name if ignorable_alias?(attribute, override) attribute.name if ignorable_alias?(attribute, override)
end end
end.compact }.compact
end end
def ignorable_alias?(attribute, override) def ignorable_alias?(attribute, override)

View File

@ -4,7 +4,7 @@ module FactoryBot
include Enumerable include Enumerable
def initialize(name = nil, attributes = []) def initialize(name = nil, attributes = [])
@name = name @name = name
@attributes = attributes @attributes = attributes
end end

View File

@ -3,7 +3,7 @@ module FactoryBot
attr_reader :name attr_reader :name
def initialize(name, block) def initialize(name, block)
@name = name.to_sym @name = name.to_sym
@block = block @block = block
end end
@ -11,7 +11,7 @@ module FactoryBot
case block.arity case block.arity
when 1, -1 then syntax_runner.instance_exec(instance, &block) when 1, -1 then syntax_runner.instance_exec(instance, &block)
when 2 then syntax_runner.instance_exec(instance, evaluator, &block) when 2 then syntax_runner.instance_exec(instance, evaluator, &block)
else syntax_runner.instance_exec(&block) else syntax_runner.instance_exec(&block)
end end
end end

View File

@ -7,16 +7,16 @@ module FactoryBot
:inline_sequences, :inline_sequences,
:sequences, :sequences,
:strategies, :strategies,
:traits, :traits
) )
def initialize def initialize
@factories = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Factory")) @factories = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Factory"))
@sequences = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Sequence")) @sequences = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Sequence"))
@traits = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Trait")) @traits = Decorator::DisallowsDuplicatesRegistry.new(Registry.new("Trait"))
@strategies = Registry.new("Strategy") @strategies = Registry.new("Strategy")
@callback_names = Set.new @callback_names = Set.new
@definition = Definition.new(:configuration) @definition = Definition.new(:configuration)
@inline_sequences = [] @inline_sequences = []
to_create(&:save!) to_create(&:save!)
@ -24,7 +24,7 @@ module FactoryBot
end end
delegate :to_create, :skip_create, :constructor, :before, :after, delegate :to_create, :skip_create, :constructor, :before, :after,
:callback, :callbacks, to: :@definition :callback, :callbacks, to: :@definition
def initialize_with(&block) def initialize_with(&block)
@definition.define_constructor(&block) @definition.define_constructor(&block)

View File

@ -8,7 +8,7 @@ module FactoryBot
attr_reader :name attr_reader :name
def initialize(name, ignored = false) def initialize(name, ignored = false)
@name = name @name = name
@ignored = ignored @ignored = ignored
end end

View File

@ -5,8 +5,8 @@ module FactoryBot
def initialize(name = nil) def initialize(name = nil)
@declarations = [] @declarations = []
@name = name @name = name
@overridable = false @overridable = false
end end
def declare_attribute(declaration) def declare_attribute(declaration)

View File

@ -4,17 +4,17 @@ module FactoryBot
attr_reader :defined_traits, :declarations, :name, :registered_enums attr_reader :defined_traits, :declarations, :name, :registered_enums
def initialize(name, base_traits = []) def initialize(name, base_traits = [])
@name = name @name = name
@declarations = DeclarationList.new(name) @declarations = DeclarationList.new(name)
@callbacks = [] @callbacks = []
@defined_traits = Set.new @defined_traits = Set.new
@registered_enums = [] @registered_enums = []
@to_create = nil @to_create = nil
@base_traits = base_traits @base_traits = base_traits
@additional_traits = [] @additional_traits = []
@constructor = nil @constructor = nil
@attributes = nil @attributes = nil
@compiled = false @compiled = false
end end
delegate :declare_attribute, to: :declarations delegate :declare_attribute, to: :declarations
@ -51,7 +51,7 @@ module FactoryBot
declarations.attributes declarations.attributes
defined_traits.each do |defined_trait| defined_traits.each do |defined_trait|
base_traits.each { |bt| bt.define_trait defined_trait } base_traits.each { |bt| bt.define_trait defined_trait }
additional_traits.each { |at| at.define_trait defined_trait } additional_traits.each { |at| at.define_trait defined_trait }
end end
@ -128,7 +128,7 @@ module FactoryBot
def initialize_copy(source) def initialize_copy(source)
super super
@attributes = nil @attributes = nil
@compiled = false @compiled = false
@defined_traits_by_name = nil @defined_traits_by_name = nil
end end
@ -138,7 +138,7 @@ module FactoryBot
[ [
base_traits.map(&method_name), base_traits.map(&method_name),
instance_exec(&block), instance_exec(&block),
additional_traits.map(&method_name), additional_traits.map(&method_name)
].flatten.compact ].flatten.compact
end end

View File

@ -1,6 +1,6 @@
module FactoryBot module FactoryBot
class DefinitionProxy class DefinitionProxy
UNPROXIED_METHODS = %w( UNPROXIED_METHODS = %w[
__send__ __send__
__id__ __id__
nil? nil?
@ -13,7 +13,7 @@ module FactoryBot
raise raise
caller caller
method method
).freeze ].freeze
(instance_methods + private_instance_methods).each do |method| (instance_methods + private_instance_methods).each do |method|
undef_method(method) unless UNPROXIED_METHODS.include?(method.to_s) undef_method(method) unless UNPROXIED_METHODS.include?(method.to_s)
@ -24,8 +24,8 @@ module FactoryBot
attr_reader :child_factories attr_reader :child_factories
def initialize(definition, ignore = false) def initialize(definition, ignore = false)
@definition = definition @definition = definition
@ignore = ignore @ignore = ignore
@child_factories = [] @child_factories = []
end end
@ -152,7 +152,7 @@ module FactoryBot
if block_given? if block_given?
raise AssociationDefinitionError.new( raise AssociationDefinitionError.new(
"Unexpected block passed to '#{name}' association "\ "Unexpected block passed to '#{name}' association "\
"in '#{@definition.name}' factory", "in '#{@definition.name}' factory"
) )
else else
declaration = Declaration::Association.new(name, *options) declaration = Declaration::Association.new(name, *options)

View File

@ -23,9 +23,9 @@ module FactoryBot
def association(factory_name, *traits_and_overrides) def association(factory_name, *traits_and_overrides)
overrides = traits_and_overrides.extract_options! overrides = traits_and_overrides.extract_options!
strategy_override = overrides.fetch(:strategy) do strategy_override = overrides.fetch(:strategy) {
FactoryBot.use_parent_strategy ? @build_strategy.class : :create FactoryBot.use_parent_strategy ? @build_strategy.class : :create
end }
traits_and_overrides += [overrides.except(:strategy)] traits_and_overrides += [overrides.except(:strategy)]
@ -33,9 +33,7 @@ module FactoryBot
@build_strategy.association(runner) @build_strategy.association(runner)
end end
def instance=(object_instance) attr_writer :instance
@instance = object_instance
end
def method_missing(method_name, *args, &block) # rubocop:disable Style/MethodMissingSuper def method_missing(method_name, *args, &block) # rubocop:disable Style/MethodMissingSuper
if @instance.respond_to?(method_name) if @instance.respond_to?(method_name)

View File

@ -3,7 +3,7 @@ module FactoryBot
class EvaluatorClassDefiner class EvaluatorClassDefiner
def initialize(attributes, parent_class) def initialize(attributes, parent_class)
@parent_class = parent_class @parent_class = parent_class
@attributes = attributes @attributes = attributes
attributes.each do |attribute| attributes.each do |attribute|
evaluator_class.define_attribute(attribute.name, &attribute.to_proc) evaluator_class.define_attribute(attribute.name, &attribute.to_proc)

View File

@ -8,23 +8,23 @@ module FactoryBot
def initialize(name, options = {}) def initialize(name, options = {})
assert_valid_options(options) assert_valid_options(options)
@name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym @name = name.respond_to?(:to_sym) ? name.to_sym : name.to_s.underscore.to_sym
@parent = options[:parent] @parent = options[:parent]
@aliases = options[:aliases] || [] @aliases = options[:aliases] || []
@class_name = options[:class] @class_name = options[:class]
@definition = Definition.new(@name, options[:traits] || []) @definition = Definition.new(@name, options[:traits] || [])
@compiled = false @compiled = false
end end
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
:defined_traits, :inherit_traits, :append_traits, to: :@definition :defined_traits, :inherit_traits, :append_traits, to: :@definition
def build_class def build_class
@build_class ||= if class_name.is_a? Class @build_class ||= if class_name.is_a? Class
class_name class_name
else else
class_name.to_s.camelize.constantize class_name.to_s.camelize.constantize
end end
end end
def run(build_strategy, overrides, &block) def run(build_strategy, overrides, &block)

View File

@ -1,11 +1,11 @@
module FactoryBot module FactoryBot
class FactoryRunner class FactoryRunner
def initialize(name, strategy, traits_and_overrides) def initialize(name, strategy, traits_and_overrides)
@name = name @name = name
@strategy = strategy @strategy = strategy
@overrides = traits_and_overrides.extract_options! @overrides = traits_and_overrides.extract_options!
@traits = traits_and_overrides @traits = traits_and_overrides
end end
def run(runner_strategy = @strategy, &block) def run(runner_strategy = @strategy, &block)
@ -22,7 +22,7 @@ module FactoryBot
strategy: runner_strategy, strategy: runner_strategy,
traits: @traits, traits: @traits,
overrides: @overrides, overrides: @overrides,
factory: factory, factory: factory
} }
ActiveSupport::Notifications.instrument("factory_bot.run_factory", instrumentation_payload) do ActiveSupport::Notifications.instrument("factory_bot.run_factory", instrumentation_payload) do

View File

@ -7,7 +7,7 @@ module FactoryBot
attr_accessor :definition_file_paths attr_accessor :definition_file_paths
end end
self.definition_file_paths = %w(factories test/factories spec/factories) self.definition_file_paths = %w[factories test/factories spec/factories]
def self.find_definitions def self.find_definitions
absolute_definition_file_paths = definition_file_paths.map { |path| File.expand_path(path) } absolute_definition_file_paths = definition_file_paths.map { |path| File.expand_path(path) }

View File

@ -3,18 +3,18 @@ module FactoryBot
module Internal module Internal
class << self class << self
delegate :after, delegate :after,
:before, :before,
:callbacks, :callbacks,
:constructor, :constructor,
:factories, :factories,
:initialize_with, :initialize_with,
:inline_sequences, :inline_sequences,
:sequences, :sequences,
:skip_create, :skip_create,
:strategies, :strategies,
:to_create, :to_create,
:traits, :traits,
to: :configuration to: :configuration
def configuration def configuration
@configuration ||= Configuration.new @configuration ||= Configuration.new

View File

@ -19,17 +19,16 @@ module FactoryBot
attr_reader :factories_to_lint, :invalid_factories, :factory_strategy attr_reader :factories_to_lint, :invalid_factories, :factory_strategy
def calculate_invalid_factories def calculate_invalid_factories
factories_to_lint.reduce(Hash.new([])) do |result, factory| factories_to_lint.each_with_object(Hash.new([])) do |factory, result|
errors = lint(factory) errors = lint(factory)
result[factory] |= errors unless errors.empty? result[factory] |= errors unless errors.empty?
result
end end
end end
class FactoryError class FactoryError
def initialize(wrapped_error, factory) def initialize(wrapped_error, factory)
@wrapped_error = wrapped_error @wrapped_error = wrapped_error
@factory = factory @factory = factory
end end
def message def message
@ -72,7 +71,7 @@ module FactoryBot
result = [] result = []
begin begin
FactoryBot.public_send(factory_strategy, factory.name) FactoryBot.public_send(factory_strategy, factory.name)
rescue StandardError => e rescue => e
result |= [FactoryError.new(e, factory)] result |= [FactoryError.new(e, factory)]
end end
result result
@ -82,16 +81,16 @@ module FactoryBot
result = [] result = []
factory.definition.defined_traits.map(&:name).each do |trait_name| factory.definition.defined_traits.map(&:name).each do |trait_name|
FactoryBot.public_send(factory_strategy, factory.name, trait_name) FactoryBot.public_send(factory_strategy, factory.name, trait_name)
rescue StandardError => e rescue => e
result |= [FactoryTraitError.new(e, factory, trait_name)] result |= [FactoryTraitError.new(e, factory, trait_name)]
end end
result result
end end
def error_message def error_message
lines = invalid_factories.map do |_factory, exceptions| lines = invalid_factories.map { |_factory, exceptions|
exceptions.map(&error_message_type) exceptions.map(&error_message_type)
end.flatten }.flatten
<<~ERROR_MESSAGE.strip <<~ERROR_MESSAGE.strip
The following factories are invalid: The following factories are invalid:

View File

@ -8,14 +8,20 @@ module FactoryBot
end end
delegate :defined_traits, :callbacks, :attributes, :constructor, delegate :defined_traits, :callbacks, :attributes, :constructor,
:to_create, to: :definition :to_create, to: :definition
def compile; end def compile
end
def class_name; end def class_name
end
def evaluator_class; FactoryBot::Evaluator; end def evaluator_class
FactoryBot::Evaluator
end
def hierarchy_class; FactoryBot::DefinitionHierarchy; end def hierarchy_class
FactoryBot::DefinitionHierarchy
end
end end
end end

View File

@ -7,7 +7,7 @@ module FactoryBot
attr_reader :name attr_reader :name
def initialize(name) def initialize(name)
@name = name @name = name
@items = ActiveSupport::HashWithIndifferentAccess.new @items = ActiveSupport::HashWithIndifferentAccess.new
end end
@ -25,7 +25,7 @@ module FactoryBot
raise key_error_with_custom_message(e) raise key_error_with_custom_message(e)
end end
alias :[] :find alias [] find
def register(name, item) def register(name, item)
@items[name] = item @items[name] = item

View File

@ -6,14 +6,14 @@ module FactoryBot
attr_reader :name attr_reader :name
def initialize(name, *args, &proc) def initialize(name, *args, &proc)
@name = name @name = name
@proc = proc @proc = proc
options = args.extract_options! options = args.extract_options!
@value = args.first || 1 @value = args.first || 1
@aliases = options.fetch(:aliases) { [] } @aliases = options.fetch(:aliases) { [] }
if !@value.respond_to?(:peek) unless @value.respond_to?(:peek)
@value = EnumeratorAdapter.new(@value) @value = EnumeratorAdapter.new(@value)
end end
end end

View File

@ -1,9 +1,11 @@
module FactoryBot module FactoryBot
module Strategy module Strategy
class Null class Null
def association(runner); end def association(runner)
end
def result(evaluation); end def result(evaluation)
end
end end
end end
end end

View File

@ -21,7 +21,7 @@ module FactoryBot
:update_attributes!, :update_attributes!,
:update_attributes, :update_attributes,
:update_column, :update_column,
:update_columns, :update_columns
].freeze ].freeze
def self.next_id=(id) def self.next_id=(id)
@ -68,7 +68,7 @@ module FactoryBot
DISABLED_PERSISTENCE_METHODS.each do |write_method| DISABLED_PERSISTENCE_METHODS.each do |write_method|
define_singleton_method(write_method) do |*args| define_singleton_method(write_method) do |*args|
raise "stubbed models are not allowed to access the database - "\ raise "stubbed models are not allowed to access the database - "\
"#{self.class}##{write_method}(#{args.join(',')})" "#{self.class}##{write_method}(#{args.join(",")})"
end end
end end
end end

View File

@ -38,12 +38,12 @@ module FactoryBot
end end
delegate :after, delegate :after,
:before, :before,
:callback, :callback,
:initialize_with, :initialize_with,
:skip_create, :skip_create,
:to_create, :to_create,
to: FactoryBot::Internal to: FactoryBot::Internal
end end
class ModifyDSL class ModifyDSL

View File

@ -15,7 +15,7 @@ module FactoryBot
end end
delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor, delegate :add_callback, :declare_attribute, :to_create, :define_trait, :constructor,
:callbacks, :attributes, to: :@definition :callbacks, :attributes, to: :@definition
def names def names
[@name] [@name]

View File

@ -12,7 +12,7 @@ describe "associations" do
expect { FactoryBot.build(:post) }.to raise_error( expect { FactoryBot.build(:post) }.to raise_error(
ArgumentError, ArgumentError,
"Association 'author' received an invalid factory argument.\n" \ "Association 'author' received an invalid factory argument.\n" \
"Did you mean? 'factory: :user'\n", "Did you mean? 'factory: :user'\n"
) )
end end
end end

View File

@ -5,8 +5,8 @@ describe "declaring attributes on a Factory that are private methods on Object"
FactoryBot.define do FactoryBot.define do
factory :website do factory :website do
system { false } system { false }
link { "http://example.com" } link { "http://example.com" }
sleep { 15 } sleep { 15 }
end end
end end
end end
@ -14,8 +14,8 @@ describe "declaring attributes on a Factory that are private methods on Object"
subject { FactoryBot.build(:website, sleep: -5) } subject { FactoryBot.build(:website, sleep: -5) }
its(:system) { should eq false } its(:system) { should eq false }
its(:link) { should eq "http://example.com" } its(:link) { should eq "http://example.com" }
its(:sleep) { should eq -5 } its(:sleep) { should eq(-5) }
end end
describe "assigning overrides that are also private methods on object" do describe "assigning overrides that are also private methods on object" do
@ -25,7 +25,8 @@ describe "assigning overrides that are also private methods on object" do
Object.class_eval do Object.class_eval do
private private
def some_funky_method(args); end def some_funky_method(args)
end
end end
FactoryBot.define do FactoryBot.define do
@ -40,9 +41,9 @@ describe "assigning overrides that are also private methods on object" do
end end
subject { FactoryBot.build(:website, format: "Great", y: 12345, some_funky_method: "foobar!") } subject { FactoryBot.build(:website, format: "Great", y: 12345, some_funky_method: "foobar!") }
its(:format) { should eq "Great" } its(:format) { should eq "Great" }
its(:y) { should eq 12345 } its(:y) { should eq 12345 }
its(:more_format) { should eq "format: Great" } its(:more_format) { should eq "format: Great" }
its(:some_funky_method) { should eq "foobar!" } its(:some_funky_method) { should eq "foobar!" }
end end
@ -62,6 +63,6 @@ describe "accessing methods from the instance within a dynamic attribute "\
end end
end end
subject { FactoryBot.build(:website) } subject { FactoryBot.build(:website) }
its(:more_format) { should eq "format: This is an awesome format" } its(:more_format) { should eq "format: This is an awesome format" }
end end

View File

@ -69,10 +69,10 @@ describe "calling `attributes_for` with a block" do
it "returns the hash of attributes" do it "returns the hash of attributes" do
expected = nil expected = nil
result = attributes_for(:company) do |attributes| result = attributes_for(:company) { |attributes|
expected = attributes expected = attributes
"hello!" "hello!"
end }
expect(result).to eq expected expect(result).to eq expected
end end
end end
@ -80,7 +80,8 @@ end
describe "`attributes_for` for a class whose constructor has required params" do describe "`attributes_for` for a class whose constructor has required params" do
before do before do
define_model("User", name: :string) do define_model("User", name: :string) do
def initialize(arg1, arg2); end def initialize(arg1, arg2)
end
end end
FactoryBot.define do FactoryBot.define do
@ -90,6 +91,6 @@ describe "`attributes_for` for a class whose constructor has required params" do
end end
end end
subject { FactoryBot.attributes_for(:user) } subject { FactoryBot.attributes_for(:user) }
its([:name]) { should eq "John Doe" } its([:name]) { should eq "John Doe" }
end end

View File

@ -9,9 +9,9 @@ describe "a generated attributes hash where order matters" do
FactoryBot.define do FactoryBot.define do
factory :parent_model do factory :parent_model do
evaluates_first { static } evaluates_first { static }
evaluates_second { evaluates_first } evaluates_second { evaluates_first }
evaluates_third { evaluates_second } evaluates_third { evaluates_second }
factory :child_model do factory :child_model do
static { 1 } static { 1 }
@ -19,9 +19,9 @@ describe "a generated attributes hash where order matters" do
end end
factory :without_parent, class: ParentModel do factory :without_parent, class: ParentModel do
evaluates_first { static } evaluates_first { static }
evaluates_second { evaluates_first } evaluates_second { evaluates_first }
evaluates_third { evaluates_second } evaluates_third { evaluates_second }
static { 1 } static { 1 }
end end
end end

View File

@ -88,10 +88,10 @@ describe "calling `build` with a block" do
it "returns the built instance" do it "returns the built instance" do
expected = nil expected = nil
result = build(:company) do |company| result = build(:company) { |company|
expected = company expected = company
"hello!" "hello!"
end }
expect(result).to eq expected expect(result).to eq expected
end end
end end

View File

@ -129,10 +129,10 @@ describe "calling `build_stubbed` with a block" do
it "returns the stub instance" do it "returns the stub instance" do
expected = nil expected = nil
result = build_stubbed(:company) do |company| result = build_stubbed(:company) { |company|
expected = company expected = company
"hello!" "hello!"
end }
expect(result).to eq expected expect(result).to eq expected
end end
end end
@ -160,8 +160,8 @@ describe "defaulting `created_at`" do
end end
it "doesn't add created_at to objects who don't have the method" do it "doesn't add created_at to objects who don't have the method" do
expect(build_stubbed(:thing_without_timestamp)). expect(build_stubbed(:thing_without_timestamp))
not_to respond_to(:created_at) .not_to respond_to(:created_at)
end end
it "allows overriding created_at for objects with created_at" do it "allows overriding created_at for objects with created_at" do
@ -171,8 +171,8 @@ describe "defaulting `created_at`" do
end end
it "doesn't allow setting created_at on an object that doesn't define it" do 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) }. expect { build_stubbed(:thing_without_timestamp, created_at: Time.now) }
to raise_error(NoMethodError, /created_at=/) .to raise_error(NoMethodError, /created_at=/)
end end
it "allows assignment of created_at" do it "allows assignment of created_at" do
@ -224,8 +224,8 @@ describe "defaulting `updated_at`" do
end end
it "doesn't add updated_at to objects who don't have the method" do it "doesn't add updated_at to objects who don't have the method" do
expect(build_stubbed(:thing_without_timestamp)). expect(build_stubbed(:thing_without_timestamp))
not_to respond_to(:updated_at) .not_to respond_to(:updated_at)
end end
it "allows overriding updated_at for objects with updated_at" do it "allows overriding updated_at for objects with updated_at" do
@ -235,9 +235,9 @@ describe "defaulting `updated_at`" do
end end
it "doesn't allow setting updated_at on an object that doesn't define it" do it "doesn't allow setting updated_at on an object that doesn't define it" do
expect do expect {
build_stubbed(:thing_without_timestamp, updated_at: Time.now) build_stubbed(:thing_without_timestamp, updated_at: Time.now)
end.to raise_error(NoMethodError, /updated_at=/) }.to raise_error(NoMethodError, /updated_at=/)
end end
it "allows assignment of updated_at" do it "allows assignment of updated_at" do

View File

@ -4,13 +4,13 @@ describe "callbacks" do
FactoryBot.define do FactoryBot.define do
factory :user_with_callbacks, class: :user do factory :user_with_callbacks, class: :user do
after(:stub) { |user| user.first_name = "Stubby" } after(:stub) { |user| user.first_name = "Stubby" }
after(:build) { |user| user.first_name = "Buildy" } after(:build) { |user| user.first_name = "Buildy" }
after(:create) { |user| user.last_name = "Createy" } after(:create) { |user| user.last_name = "Createy" }
end end
factory :user_with_inherited_callbacks, parent: :user_with_callbacks do factory :user_with_inherited_callbacks, parent: :user_with_callbacks do
after(:stub) { |user| user.last_name = "Double-Stubby" } after(:stub) { |user| user.last_name = "Double-Stubby" }
after(:build) { |user| user.first_name = "Child-Buildy" } after(:build) { |user| user.first_name = "Child-Buildy" }
end end
end end
@ -79,8 +79,8 @@ describe "callbacks using syntax methods without referencing FactoryBot explicit
sequence(:sequence_3) sequence(:sequence_3)
factory :user do factory :user do
after(:stub) { generate(:sequence_3) } after(:stub) { generate(:sequence_3) }
after(:build) { |user| user.first_number = generate(:sequence_1) } after(:build) { |user| user.first_number = generate(:sequence_1) }
after(:create) { |user, _evaluator| user.last_number = generate(:sequence_2) } after(:create) { |user, _evaluator| user.last_number = generate(:sequence_2) }
end end
end end
@ -145,13 +145,13 @@ describe "custom callbacks" do
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
first_name { "John" } first_name { "John" }
last_name { "Doe" } last_name { "Doe" }
before(:custom) { |instance| instance.first_name = "Overridden First" } before(:custom) { |instance| instance.first_name = "Overridden First" }
after(:custom) { |instance| instance.last_name = "Overridden Last" } after(:custom) { |instance| instance.last_name = "Overridden Last" }
callback(:totally_custom) do |instance| callback(:totally_custom) do |instance|
instance.first_name = "Totally" instance.first_name = "Totally"
instance.last_name = "Custom" instance.last_name = "Custom"
end end
end end
end end
@ -211,7 +211,7 @@ describe "global callbacks" do
object.name = case object.class.to_s object.name = case object.class.to_s
when "User" then "John Doe" when "User" then "John Doe"
when "Company" then "Acme Suppliers" when "Company" then "Acme Suppliers"
end end
end end
after :create do |object| after :create do |object|

View File

@ -125,10 +125,10 @@ describe "calling `create` with a block" do
it "returns the created instance" do it "returns the created instance" do
expected = nil expected = nil
result = create(:company) do |company| result = create(:company) { |company|
expected = company expected = company
"hello!" "hello!"
end }
expect(result).to eq expected expect(result).to eq expected
end end
end end

View File

@ -14,7 +14,7 @@ describe "defining methods inside FactoryBot" do
expect(bad_factory_definition).to raise_error( expect(bad_factory_definition).to raise_error(
FactoryBot::MethodDefinitionError, FactoryBot::MethodDefinitionError,
/Defining methods in blocks \(trait or factory\) is not supported \(generate_name\)/, /Defining methods in blocks \(trait or factory\) is not supported \(generate_name\)/
) )
end end
end end

View File

@ -8,7 +8,7 @@ describe "an instance generated by a factory named a camel case string " do
end end
it "registers the UserModel factory" do it "registers the UserModel factory" do
expect(FactoryBot::Internal.factory_by_name("UserModel")). expect(FactoryBot::Internal.factory_by_name("UserModel"))
to be_a(FactoryBot::Factory) .to be_a(FactoryBot::Factory)
end end
end end

View File

@ -24,7 +24,7 @@ describe "attributes defined using Symbol#to_proc" do
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
password { "foo" } password { "foo" }
password_confirmation &:password password_confirmation(&:password)
end end
end end
end end

View File

@ -8,7 +8,7 @@ describe "an instance generated by a factory" do
end end
it "registers the user factory" do it "registers the user factory" do
expect(FactoryBot::Internal.factory_by_name(:user)). expect(FactoryBot::Internal.factory_by_name(:user))
to be_a(FactoryBot::Factory) .to be_a(FactoryBot::Factory)
end end
end end

View File

@ -2,7 +2,7 @@ describe "enum traits" do
context "when automatically_define_enum_traits is true" do context "when automatically_define_enum_traits is true" do
it "builds traits automatically for model enum field" do it "builds traits automatically for model enum field" do
define_model("Task", status: :integer) do define_model("Task", status: :integer) do
enum status: { queued: 0, started: 1, finished: 2 } enum status: {queued: 0, started: 1, finished: 2}
end end
FactoryBot.define do FactoryBot.define do
@ -20,7 +20,7 @@ describe "enum traits" do
it "prefers user defined traits over automatically built traits" do it "prefers user defined traits over automatically built traits" do
define_model("Task", status: :integer) do define_model("Task", status: :integer) do
enum status: { queued: 0, started: 1, finished: 2 } enum status: {queued: 0, started: 1, finished: 2}
end end
FactoryBot.define do FactoryBot.define do
@ -49,7 +49,7 @@ describe "enum traits" do
end end
it "builds traits for each enumerated value using a provided list of values as a Hash" do it "builds traits for each enumerated value using a provided list of values as a Hash" do
statuses = { queued: 0, started: 1, finished: 2 } statuses = {queued: 0, started: 1, finished: 2}
define_class "Task" do define_class "Task" do
attr_accessor :status attr_accessor :status
@ -89,13 +89,13 @@ describe "enum traits" do
end end
it "builds traits for each enumerated value using a custom enumerable" do it "builds traits for each enumerated value using a custom enumerable" do
statuses = define_class("Statuses") do statuses = define_class("Statuses") {
include Enumerable include Enumerable
def each(&block) def each(&block)
["queued", "started", "finished"].each(&block) ["queued", "started", "finished"].each(&block)
end end
end.new }.new
define_class "Task" do define_class "Task" do
attr_accessor :status attr_accessor :status
@ -119,7 +119,7 @@ describe "enum traits" do
it "raises an error for undefined traits" do it "raises an error for undefined traits" do
with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do
define_model("Task", status: :integer) do define_model("Task", status: :integer) do
enum status: { queued: 0, started: 1, finished: 2 } enum status: {queued: 0, started: 1, finished: 2}
end end
FactoryBot.define do FactoryBot.define do
@ -139,7 +139,7 @@ describe "enum traits" do
it "builds traits for each enumerated value when traits_for_enum are specified" do it "builds traits for each enumerated value when traits_for_enum are specified" do
with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do with_temporary_assignment(FactoryBot, :automatically_define_enum_traits, false) do
define_model("Task", status: :integer) do define_model("Task", status: :integer) do
enum status: { queued: 0, started: 1, finished: 2 } enum status: {queued: 0, started: 1, finished: 2}
end end
FactoryBot.define do FactoryBot.define do

View File

@ -15,9 +15,9 @@ describe "initialize_with with non-FG attributes" do
end end
end end
subject { build(:user) } subject { build(:user) }
its(:name) { should eq "John Doe" } its(:name) { should eq "John Doe" }
its(:age) { should eq 21 } its(:age) { should eq 21 }
end end
describe "initialize_with with FG attributes that are transient" do describe "initialize_with with FG attributes that are transient" do
@ -41,7 +41,7 @@ describe "initialize_with with FG attributes that are transient" do
end end
end end
subject { build(:user) } subject { build(:user) }
its(:name) { should eq "Handsome Chap from .construct" } its(:name) { should eq "Handsome Chap from .construct" }
end end
@ -163,7 +163,7 @@ describe "initialize_with doesn't duplicate assignment on attributes accessed fr
factory :user do factory :user do
email email
name { email.gsub(/\@.+/, "") } name { email.gsub(/@.+/, "") }
initialize_with { new(name) } initialize_with { new(name) }
end end
@ -199,7 +199,7 @@ describe "initialize_with has access to all attributes for construction" do
email email
name { email.gsub(/\@.+/, "") } name { email.gsub(/@.+/, "") }
initialize_with { new(attributes) } initialize_with { new(attributes) }
end end
@ -224,7 +224,7 @@ describe "initialize_with with an 'attributes' attribute" do
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
attributes { { name: "Daniel" } } attributes { {name: "Daniel"} }
initialize_with { new(attributes) } initialize_with { new(attributes) }
end end
end end

View File

@ -11,7 +11,7 @@ describe "finding factories keyed by class instead of symbol" do
it "doesn't find the factory" do it "doesn't find the factory" do
expect { FactoryBot.create(User) }.to( expect { FactoryBot.create(User) }.to(
raise_error(KeyError, /Factory not registered: User/), raise_error(KeyError, /Factory not registered: User/)
) )
end end
end end

View File

@ -21,9 +21,9 @@ describe "FactoryBot.lint" do
* admin_user - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid) * admin_user - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid)
ERROR_MESSAGE ERROR_MESSAGE
expect do expect {
FactoryBot.lint FactoryBot.lint
end.to raise_error FactoryBot::InvalidFactoryError, error_message }.to raise_error FactoryBot::InvalidFactoryError, error_message
end end
it "does not raise when all factories are valid" do it "does not raise when all factories are valid" do
@ -52,13 +52,13 @@ describe "FactoryBot.lint" do
factory :invalid_thing factory :invalid_thing
end end
expect do expect {
only_valid_factories = FactoryBot.factories.reject do |factory| only_valid_factories = FactoryBot.factories.reject { |factory|
factory.name =~ /invalid/ factory.name =~ /invalid/
end }
FactoryBot.lint only_valid_factories FactoryBot.lint only_valid_factories
end.not_to raise_error }.not_to raise_error
end end
describe "trait validation" do describe "trait validation" do
@ -83,9 +83,9 @@ describe "FactoryBot.lint" do
* user+unnamed - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid) * user+unnamed - Validation failed: Name can't be blank (ActiveRecord::RecordInvalid)
ERROR_MESSAGE ERROR_MESSAGE
expect do expect {
FactoryBot.lint traits: true FactoryBot.lint traits: true
end.to raise_error FactoryBot::InvalidFactoryError, error_message }.to raise_error FactoryBot::InvalidFactoryError, error_message
end end
it "does not raise if a trait produces a valid object" do it "does not raise if a trait produces a valid object" do
@ -102,9 +102,9 @@ describe "FactoryBot.lint" do
end end
end end
expect do expect {
FactoryBot.lint traits: true FactoryBot.lint traits: true
end.not_to raise_error }.not_to raise_error
end end
end end
@ -123,10 +123,10 @@ describe "FactoryBot.lint" do
end end
end end
expect do expect {
FactoryBot.lint traits: false FactoryBot.lint traits: false
FactoryBot.lint FactoryBot.lint
end.not_to raise_error }.not_to raise_error
end end
end end
end end
@ -147,9 +147,9 @@ describe "FactoryBot.lint" do
end end
end end
expect do expect {
FactoryBot.lint strategy: :build FactoryBot.lint strategy: :build
end.not_to raise_error }.not_to raise_error
end end
it "uses the requested strategy during trait validation" do it "uses the requested strategy during trait validation" do
@ -171,9 +171,9 @@ describe "FactoryBot.lint" do
end end
end end
expect do expect {
FactoryBot.lint traits: true, strategy: :build FactoryBot.lint traits: true, strategy: :build
end.not_to raise_error }.not_to raise_error
end end
end end
@ -189,11 +189,11 @@ describe "FactoryBot.lint" do
factory :invalid_thing factory :invalid_thing
end end
expect do expect {
FactoryBot.lint(verbose: true) FactoryBot.lint(verbose: true)
end.to raise_error( }.to raise_error(
FactoryBot::InvalidFactoryError, FactoryBot::InvalidFactoryError,
%r{#{__FILE__}:\d*:in `save!'}, %r{#{__FILE__}:\d*:in `save!'}
) )
end end
end end

View File

@ -30,14 +30,14 @@ describe "modifying factories" do
end end
end end
subject { create(:user) } subject { create(:user) }
its(:name) { should eq "Great User" } its(:name) { should eq "Great User" }
its(:login) { should eq "GREAT USER" } its(:login) { should eq "GREAT USER" }
it "doesn't allow the factory to be subsequently defined" do it "doesn't allow the factory to be subsequently defined" do
expect do expect {
FactoryBot.define { factory :user } FactoryBot.define { factory :user }
end.to raise_error(FactoryBot::DuplicateDefinitionError, "Factory already registered: user") }.to raise_error(FactoryBot::DuplicateDefinitionError, "Factory already registered: user")
end end
it "does allow the factory to be subsequently modified" do it "does allow the factory to be subsequently modified" do
@ -66,7 +66,7 @@ describe "modifying factories" do
subject { create(:user) } subject { create(:user) }
its(:name) { should eq "great user" } its(:name) { should eq "great user" }
its(:login) { should be_nil } its(:login) { should be_nil }
end end
@ -86,9 +86,9 @@ describe "modifying factories" do
end end
end end
subject { create(:user) } subject { create(:user) }
its(:name) { should eq "Johnny Rockstar!!!" } its(:name) { should eq "Johnny Rockstar!!!" }
its(:email) { should eq "Johnny Rockstar!!!@example.com" } its(:email) { should eq "Johnny Rockstar!!!@example.com" }
its(:login) { should eq "JOHNNY ROCKSTAR!!!" } its(:login) { should eq "JOHNNY ROCKSTAR!!!" }
end end
@ -105,48 +105,48 @@ describe "modifying factories" do
context "creating user" do context "creating user" do
context "without overrides" do context "without overrides" do
subject { create(:user) } subject { create(:user) }
its(:name) { should eq "Great User" } its(:name) { should eq "Great User" }
its(:email) { should eq "Great User-modified@example.com" } its(:email) { should eq "Great User-modified@example.com" }
end end
context "overriding the email" do context "overriding the email" do
subject { create(:user, email: "perfect@example.com") } subject { create(:user, email: "perfect@example.com") }
its(:name) { should eq "Great User" } its(:name) { should eq "Great User" }
its(:email) { should eq "perfect@example.com" } its(:email) { should eq "perfect@example.com" }
end end
context "overriding the name" do context "overriding the name" do
subject { create(:user, name: "wonderful") } subject { create(:user, name: "wonderful") }
its(:name) { should eq "wonderful" } its(:name) { should eq "wonderful" }
its(:email) { should eq "wonderful-modified@example.com" } its(:email) { should eq "wonderful-modified@example.com" }
end end
end end
context "creating admin" do context "creating admin" do
context "without overrides" do context "without overrides" do
subject { create(:admin) } subject { create(:admin) }
its(:name) { should eq "Great User" } its(:name) { should eq "Great User" }
its(:email) { should eq "Great User-modified@example.com" } its(:email) { should eq "Great User-modified@example.com" }
its(:admin) { should be true } its(:admin) { should be true }
end end
context "overriding the email" do context "overriding the email" do
subject { create(:admin, email: "perfect@example.com") } subject { create(:admin, email: "perfect@example.com") }
its(:name) { should eq "Great User" } its(:name) { should eq "Great User" }
its(:email) { should eq "perfect@example.com" } its(:email) { should eq "perfect@example.com" }
its(:admin) { should be true } its(:admin) { should be true }
end end
context "overriding the name" do context "overriding the name" do
subject { create(:admin, name: "wonderful") } subject { create(:admin, name: "wonderful") }
its(:name) { should eq "wonderful" } its(:name) { should eq "wonderful" }
its(:email) { should eq "wonderful-modified@example.com" } its(:email) { should eq "wonderful-modified@example.com" }
its(:admin) { should be true } its(:admin) { should be true }
end end

View File

@ -4,11 +4,11 @@ describe "modifying inherited factories with traits" do
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
trait(:female) { gender { "Female" } } trait(:female) { gender { "Female" } }
trait(:male) { gender { "Male" } } trait(:male) { gender { "Male" } }
trait(:young_admin) do trait(:young_admin) do
admin { true } admin { true }
age { 17 } age { 17 }
end end
female female

View File

@ -30,7 +30,7 @@ describe "attribute overrides" do
let(:admin) { FactoryBot.create(:admin) } let(:admin) { FactoryBot.create(:admin) }
let(:post_attributes) do let(:post_attributes) do
{ secure: false } {secure: false}
end end
let(:non_admin_post_attributes) do let(:non_admin_post_attributes) do
@ -44,17 +44,17 @@ describe "attribute overrides" do
end end
context "with an admin posting" do context "with an admin posting" do
subject { FactoryBot.create(:post, admin_post_attributes) } subject { FactoryBot.create(:post, admin_post_attributes) }
its(:secure) { should eq false } its(:secure) { should eq false }
end end
context "with a non-admin posting" do context "with a non-admin posting" do
subject { FactoryBot.create(:post, non_admin_post_attributes) } subject { FactoryBot.create(:post, non_admin_post_attributes) }
its(:secure) { should be_nil } its(:secure) { should be_nil }
end end
context "with no user posting" do context "with no user posting" do
subject { FactoryBot.create(:post, post_attributes) } subject { FactoryBot.create(:post, post_attributes) }
its(:secure) { should be_nil } its(:secure) { should be_nil }
end end
end end

View File

@ -4,7 +4,7 @@ describe "an instance generated by a factory that inherits from another factory"
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
name { "John" } name { "John" }
email { "#{name.downcase}@example.com" } email { "#{name.downcase}@example.com" }
login { email } login { email }
@ -18,20 +18,20 @@ describe "an instance generated by a factory that inherits from another factory"
end end
describe "the parent class" do describe "the parent class" do
subject { FactoryBot.create(:user) } subject { FactoryBot.create(:user) }
it { should_not be_admin } it { should_not be_admin }
its(:name) { should eq "John" } its(:name) { should eq "John" }
its(:email) { should eq "john@example.com" } its(:email) { should eq "john@example.com" }
its(:login) { should eq "john@example.com" } its(:login) { should eq "john@example.com" }
end end
describe "the child class redefining parent's attributes" do describe "the child class redefining parent's attributes" do
subject { FactoryBot.create(:admin) } subject { FactoryBot.create(:admin) }
it { should be_kind_of(User) } it { should be_kind_of(User) }
it { should be_admin } it { should be_admin }
its(:name) { should eq "admin" } its(:name) { should eq "admin" }
its(:email) { should eq "admin@example.com" } its(:email) { should eq "admin@example.com" }
its(:login) { should eq "admin@example.com" } its(:login) { should eq "admin@example.com" }
its(:upper_email) { should eq "ADMIN@EXAMPLE.COM" } its(:upper_email) { should eq "ADMIN@EXAMPLE.COM" }
end end
end end
@ -42,7 +42,7 @@ describe "nested factories with different parents" do
FactoryBot.define do FactoryBot.define do
factory :user do factory :user do
name { "Basic User" } name { "Basic User" }
factory :male_user do factory :male_user do
name { "John Doe" } name { "John Doe" }

View File

@ -12,8 +12,8 @@ describe "setting private attributes" do
end end
end end
expect do expect {
FactoryBot.build(:user) FactoryBot.build(:user)
end.to raise_error NoMethodError, /foo=/ }.to raise_error NoMethodError, /foo=/
end end
end end

View File

@ -11,8 +11,8 @@ describe "sequences" do
first_value = generate(:email) first_value = generate(:email)
another_value = generate(:email) another_value = generate(:email)
expect(first_value).to match /^somebody\d+@example\.com$/ expect(first_value).to match(/^somebody\d+@example\.com$/)
expect(another_value).to match /^somebody\d+@example\.com$/ expect(another_value).to match(/^somebody\d+@example\.com$/)
expect(first_value).not_to eq another_value expect(first_value).not_to eq another_value
end end
@ -34,9 +34,9 @@ describe "sequences" do
sequence(:size, aliases: [:count, :length]) { |n| "called-#{n}" } sequence(:size, aliases: [:count, :length]) { |n| "called-#{n}" }
end end
first_value = generate(:size) first_value = generate(:size)
second_value = generate(:count) second_value = generate(:count)
third_value = generate(:length) third_value = generate(:length)
expect(first_value).to eq "called-1" expect(first_value).to eq "called-1"
expect(second_value).to eq "called-2" expect(second_value).to eq "called-2"
@ -48,9 +48,9 @@ describe "sequences" do
sequence(:size, "a", aliases: [:count, :length]) { |n| "called-#{n}" } sequence(:size, "a", aliases: [:count, :length]) { |n| "called-#{n}" }
end end
first_value = generate(:size) first_value = generate(:size)
second_value = generate(:count) second_value = generate(:count)
third_value = generate(:length) third_value = generate(:length)
expect(first_value).to eq "called-a" expect(first_value).to eq "called-a"
expect(second_value).to eq "called-b" expect(second_value).to eq "called-b"

View File

@ -1,12 +1,12 @@
describe "an instance generated by a factory with multiple traits" do describe "an instance generated by a factory with multiple traits" do
before do before do
define_model("User", define_model("User",
name: :string, name: :string,
admin: :boolean, admin: :boolean,
gender: :string, gender: :string,
email: :string, email: :string,
date_of_birth: :date, date_of_birth: :date,
great: :string) great: :string)
FactoryBot.define do FactoryBot.define do
factory :user_without_admin_scoping, class: User do factory :user_without_admin_scoping, class: User do
@ -33,12 +33,12 @@ describe "an instance generated by a factory with multiple traits" do
end end
trait :male do trait :male do
name { "Joe" } name { "Joe" }
gender { "Male" } gender { "Male" }
end end
trait :female do trait :female do
name { "Jane" } name { "Jane" }
gender { "Female" } gender { "Female" }
end end
@ -77,7 +77,7 @@ describe "an instance generated by a factory with multiple traits" do
factory :female_admin_judy, traits: [:admin] factory :female_admin_judy, traits: [:admin]
end end
factory :female_admin, traits: [:female, :admin] factory :female_admin, traits: [:female, :admin]
factory :female_after_male_admin, traits: [:male, :female, :admin] factory :female_after_male_admin, traits: [:male, :female, :admin]
factory :male_after_female_admin, traits: [:female, :male, :admin] factory :male_after_female_admin, traits: [:female, :male, :admin]
end end
@ -93,97 +93,97 @@ describe "an instance generated by a factory with multiple traits" do
end end
context "the parent class" do context "the parent class" do
subject { FactoryBot.create(:user) } subject { FactoryBot.create(:user) }
its(:name) { should eq "John" } its(:name) { should eq "John" }
its(:gender) { should be_nil } its(:gender) { should be_nil }
it { should_not be_admin } it { should_not be_admin }
end end
context "the child class with one trait" do context "the child class with one trait" do
subject { FactoryBot.create(:admin) } subject { FactoryBot.create(:admin) }
its(:name) { should eq "John" } its(:name) { should eq "John" }
its(:gender) { should be_nil } its(:gender) { should be_nil }
it { should be_admin } it { should be_admin }
end end
context "the other child class with one trait" do context "the other child class with one trait" do
subject { FactoryBot.create(:female) } subject { FactoryBot.create(:female) }
its(:name) { should eq "Jane" } its(:name) { should eq "Jane" }
its(:gender) { should eq "Female" } its(:gender) { should eq "Female" }
it { should_not be_admin } it { should_not be_admin }
end end
context "the child with multiple traits" do context "the child with multiple traits" do
subject { FactoryBot.create(:female_admin) } subject { FactoryBot.create(:female_admin) }
its(:name) { should eq "Jane" } its(:name) { should eq "Jane" }
its(:gender) { should eq "Female" } its(:gender) { should eq "Female" }
it { should be_admin } it { should be_admin }
end end
context "the child with multiple traits and overridden attributes" do context "the child with multiple traits and overridden attributes" do
subject { FactoryBot.create(:female_admin, name: "Jill", gender: nil) } subject { FactoryBot.create(:female_admin, name: "Jill", gender: nil) }
its(:name) { should eq "Jill" } its(:name) { should eq "Jill" }
its(:gender) { should be_nil } its(:gender) { should be_nil }
it { should be_admin } it { should be_admin }
end end
context "the child with multiple traits who override the same attribute" do context "the child with multiple traits who override the same attribute" do
context "when the male assigns name after female" do context "when the male assigns name after female" do
subject { FactoryBot.create(:male_after_female_admin) } subject { FactoryBot.create(:male_after_female_admin) }
its(:name) { should eq "Joe" } its(:name) { should eq "Joe" }
its(:gender) { should eq "Male" } its(:gender) { should eq "Male" }
it { should be_admin } it { should be_admin }
end end
context "when the female assigns name after male" do context "when the female assigns name after male" do
subject { FactoryBot.create(:female_after_male_admin) } subject { FactoryBot.create(:female_after_male_admin) }
its(:name) { should eq "Jane" } its(:name) { should eq "Jane" }
its(:gender) { should eq "Female" } its(:gender) { should eq "Female" }
it { should be_admin } it { should be_admin }
end end
end end
context "child class with scoped trait and inherited trait" do context "child class with scoped trait and inherited trait" do
subject { FactoryBot.create(:female_admin_judy) } subject { FactoryBot.create(:female_admin_judy) }
its(:name) { should eq "Judy" } its(:name) { should eq "Judy" }
its(:gender) { should eq "Female" } its(:gender) { should eq "Female" }
it { should be_admin } it { should be_admin }
end end
context "factory using global trait" do context "factory using global trait" do
subject { FactoryBot.create(:user_with_email) } subject { FactoryBot.create(:user_with_email) }
its(:name) { should eq "Bill" } its(:name) { should eq "Bill" }
its(:email) { should eq "Bill@example.com" } its(:email) { should eq "Bill@example.com" }
end end
context "factory created with alternate syntax for specifying trait" do context "factory created with alternate syntax for specifying trait" do
subject { FactoryBot.create(:male_user) } subject { FactoryBot.create(:male_user) }
its(:gender) { should eq "Male" } its(:gender) { should eq "Male" }
context "where trait name and attribute are the same" do context "where trait name and attribute are the same" do
subject { FactoryBot.create(:great_user) } subject { FactoryBot.create(:great_user) }
its(:great) { should eq "GREAT!!!" } its(:great) { should eq "GREAT!!!" }
end end
context "where trait name and attribute are the same and attribute is overridden" do context "where trait name and attribute are the same and attribute is overridden" do
subject { FactoryBot.create(:great_user, great: "SORT OF!!!") } subject { FactoryBot.create(:great_user, great: "SORT OF!!!") }
its(:great) { should eq "SORT OF!!!" } its(:great) { should eq "SORT OF!!!" }
end end
end end
context "factory with trait defined multiple times" do context "factory with trait defined multiple times" do
subject { FactoryBot.create(:great_user) } subject { FactoryBot.create(:great_user) }
its(:great) { should eq "GREAT!!!" } its(:great) { should eq "GREAT!!!" }
context "child factory redefining trait" do context "child factory redefining trait" do
subject { FactoryBot.create(:even_greater_user) } subject { FactoryBot.create(:even_greater_user) }
its(:great) { should eq "EVEN GREATER!!!" } its(:great) { should eq "EVEN GREATER!!!" }
end end
end end
context "child factory created where trait attributes are inherited" do context "child factory created where trait attributes are inherited" do
subject { FactoryBot.create(:child_male_user) } subject { FactoryBot.create(:child_male_user) }
its(:gender) { should eq "Male" } its(:gender) { should eq "Male" }
its(:date_of_birth) { should eq Date.parse("1/1/2000") } its(:date_of_birth) { should eq Date.parse("1/1/2000") }
end end
@ -191,13 +191,13 @@ describe "an instance generated by a factory with multiple traits" do
subject { FactoryBot.create(:user_without_admin_scoping) } subject { FactoryBot.create(:user_without_admin_scoping) }
it "raises an error" do it "raises an error" do
expect { subject }. expect { subject }
to raise_error(KeyError, "Trait not registered: \"admin_trait\"") .to raise_error(KeyError, "Trait not registered: \"admin_trait\"")
end end
end end
context "child factory using grandparents' trait" do context "child factory using grandparents' trait" do
subject { FactoryBot.create(:female_great_user) } subject { FactoryBot.create(:female_great_user) }
its(:great) { should eq "GREAT!!!" } its(:great) { should eq "GREAT!!!" }
end end
end end
@ -300,8 +300,8 @@ describe "looking up traits that don't exist" do
factory :user factory :user
end end
expect { FactoryBot.build(:user, double("not a trait")) }. expect { FactoryBot.build(:user, double("not a trait")) }
to raise_error(KeyError) .to raise_error(KeyError)
end end
end end
@ -332,12 +332,12 @@ describe "traits with callbacks" do
end end
context "when the factory has a trait passed via arguments" do context "when the factory has a trait passed via arguments" do
subject { FactoryBot.create(:caps_user) } subject { FactoryBot.create(:caps_user) }
its(:name) { should eq "JOHN" } its(:name) { should eq "JOHN" }
end end
context "when the factory has an implicit trait" do context "when the factory has an implicit trait" do
subject { FactoryBot.create(:caps_user_implicit_trait) } subject { FactoryBot.create(:caps_user_implicit_trait) }
its(:name) { should eq "JOHN" } its(:name) { should eq "JOHN" }
end end
@ -369,7 +369,7 @@ describe "traits added via strategy" do
subject { FactoryBot.create(:user, :admin, :great, name: "Joe") } subject { FactoryBot.create(:user, :admin, :great, name: "Joe") }
its(:admin) { should be true } its(:admin) { should be true }
its(:name) { should eq "JOE" } its(:name) { should eq "JOE" }
it "doesn't modify the user factory" do it "doesn't modify the user factory" do
subject subject
@ -382,21 +382,21 @@ describe "traits added via strategy" do
subject { FactoryBot.build(:user, :admin, :great, name: "Joe") } subject { FactoryBot.build(:user, :admin, :great, name: "Joe") }
its(:admin) { should be true } its(:admin) { should be true }
its(:name) { should eq "Joe" } its(:name) { should eq "Joe" }
end end
context "adding traits in attributes_for" do context "adding traits in attributes_for" do
subject { FactoryBot.attributes_for(:user, :admin, :great) } subject { FactoryBot.attributes_for(:user, :admin, :great) }
its([:admin]) { should be true } its([:admin]) { should be true }
its([:name]) { should eq "John" } its([:name]) { should eq "John" }
end end
context "adding traits in build_stubbed" do context "adding traits in build_stubbed" do
subject { FactoryBot.build_stubbed(:user, :admin, :great, name: "Jack") } subject { FactoryBot.build_stubbed(:user, :admin, :great, name: "Jack") }
its(:admin) { should be true } its(:admin) { should be true }
its(:name) { should eq "Jack" } its(:name) { should eq "Jack" }
end end
context "adding traits in create_list" do context "adding traits in create_list" do
@ -443,9 +443,9 @@ describe "traits and dynamic attributes that are applied simultaneously" do
end end
end end
subject { FactoryBot.build(:user) } subject { FactoryBot.build(:user) }
its(:name) { should eq "John" } its(:name) { should eq "John" }
its(:email) { should eq "John@example.com" } its(:email) { should eq "John@example.com" }
its(:combined) { should eq "John <John@example.com>" } its(:combined) { should eq "John <John@example.com>" }
end end
@ -872,7 +872,7 @@ describe "when a self-referential trait is defined" do
expect { FactoryBot.build(:user, :admin) }.to raise_error( expect { FactoryBot.build(:user, :admin) }.to raise_error(
FactoryBot::TraitDefinitionError, FactoryBot::TraitDefinitionError,
"Self-referencing trait 'admin'", "Self-referencing trait 'admin'"
) )
end end
@ -889,7 +889,7 @@ describe "when a self-referential trait is defined" do
expect { FactoryBot.build(:user, :admin) }.to raise_error( expect { FactoryBot.build(:user, :admin) }.to raise_error(
FactoryBot::TraitDefinitionError, FactoryBot::TraitDefinitionError,
"Self-referencing trait 'admin'", "Self-referencing trait 'admin'"
) )
end end
end end

View File

@ -7,12 +7,12 @@ describe "transient attributes" do
factory :user do factory :user do
transient do transient do
four { 2 + 2 } four { 2 + 2 }
rockstar { true } rockstar { true }
upcased { false } upcased { false }
end end
name { "#{FactoryBot.generate(:name)}#{' - Rockstar' if rockstar}" } name { "#{FactoryBot.generate(:name)}#{" - Rockstar" if rockstar}" }
email { "#{name.downcase}#{four}@example.com" } email { "#{name.downcase}#{four}@example.com" }
after(:create) do |user, evaluator| after(:create) do |user, evaluator|
@ -27,15 +27,15 @@ describe "transient attributes" do
it { should_not have_key(:four) } it { should_not have_key(:four) }
it { should_not have_key(:rockstar) } it { should_not have_key(:rockstar) }
it { should_not have_key(:upcased) } it { should_not have_key(:upcased) }
it { should have_key(:name) } it { should have_key(:name) }
it { should have_key(:email) } it { should have_key(:email) }
end end
context "with a transient variable assigned" do context "with a transient variable assigned" do
let(:rockstar) { FactoryBot.create(:user, rockstar: true, four: "1234") } let(:rockstar) { FactoryBot.create(:user, rockstar: true, four: "1234") }
let(:rockstar_with_name) { FactoryBot.create(:user, name: "Jane Doe", rockstar: true) } let(:rockstar_with_name) { FactoryBot.create(:user, name: "Jane Doe", rockstar: true) }
let(:upcased_rockstar) { FactoryBot.create(:user, rockstar: true, upcased: true) } let(:upcased_rockstar) { FactoryBot.create(:user, rockstar: true, upcased: true) }
let(:groupie) { FactoryBot.create(:user, rockstar: false) } let(:groupie) { FactoryBot.create(:user, rockstar: false) }
it "generates the correct attributes on a rockstar" do it "generates the correct attributes on a rockstar" do
expect(rockstar.name).to eq "John 1 - Rockstar" expect(rockstar.name).to eq "John 1 - Rockstar"
@ -108,7 +108,7 @@ describe "assigning values from a transient attribute" do
foo { Foo.new("id-of-foo", "name-of-foo") } foo { Foo.new("id-of-foo", "name-of-foo") }
end end
foo_id { foo.id } foo_id { foo.id }
foo_name { foo.name } foo_name { foo.name }
end end
end end

View File

@ -1,13 +1,14 @@
describe FactoryBot::Attribute::Association do describe FactoryBot::Attribute::Association do
let(:name) { :author } let(:name) { :author }
let(:factory) { :user } let(:factory) { :user }
let(:overrides) { { first_name: "John" } } let(:overrides) { {first_name: "John"} }
let(:association) { double("association") } let(:association) { double("association") }
subject { FactoryBot::Attribute::Association.new(name, factory, overrides) } subject { FactoryBot::Attribute::Association.new(name, factory, overrides) }
module MissingMethods module MissingMethods
def association(*args); end def association(*args)
end
end end
before do before do
@ -15,11 +16,11 @@ describe FactoryBot::Attribute::Association do
# Ususually this is determined via '#method_missing' # Ususually this is determined via '#method_missing'
subject.extend(MissingMethods) subject.extend(MissingMethods)
allow(subject). allow(subject)
to receive(:association).with(any_args).and_return association .to receive(:association).with(any_args).and_return association
end end
it { should be_association } it { should be_association }
its(:name) { should eq name } its(:name) { should eq name }
it "builds the association when calling the proc" do it "builds the association when calling the proc" do
@ -33,6 +34,6 @@ describe FactoryBot::Attribute::Association do
end end
describe FactoryBot::Attribute::Association, "with a string name" do describe FactoryBot::Attribute::Association, "with a string name" do
subject { FactoryBot::Attribute::Association.new("name", :user, {}) } subject { FactoryBot::Attribute::Association.new("name", :user, {}) }
its(:name) { should eq :name } its(:name) { should eq :name }
end end

View File

@ -1,5 +1,5 @@
describe FactoryBot::Attribute::Dynamic do describe FactoryBot::Attribute::Dynamic do
let(:name) { :first_name } let(:name) { :first_name }
let(:block) { -> {} } let(:block) { -> {} }
subject { FactoryBot::Attribute::Dynamic.new(name, false, block) } subject { FactoryBot::Attribute::Dynamic.new(name, false, block) }
@ -23,11 +23,12 @@ describe FactoryBot::Attribute::Dynamic do
end end
context "with a block referencing an attribute on the attribute" do context "with a block referencing an attribute on the attribute" do
let(:block) { -> { attribute_defined_on_attribute } } let(:block) { -> { attribute_defined_on_attribute } }
let(:result) { "other attribute value" } let(:result) { "other attribute value" }
module MissingMethods module MissingMethods
def attribute_defined_on_attribute(*args); end def attribute_defined_on_attribute(*args)
end
end end
before do before do
@ -35,8 +36,8 @@ describe FactoryBot::Attribute::Dynamic do
# be mocked. Ususually this is determined via '#method_missing' # be mocked. Ususually this is determined via '#method_missing'
subject.extend(MissingMethods) subject.extend(MissingMethods)
allow(subject). allow(subject)
to receive(:attribute_defined_on_attribute).and_return result .to receive(:attribute_defined_on_attribute).and_return result
end end
it "evaluates the attribute from the attribute" do it "evaluates the attribute from the attribute" do
@ -48,7 +49,7 @@ describe FactoryBot::Attribute::Dynamic do
let(:block) do let(:block) do
-> do -> do
FactoryBot::Internal.register_sequence( FactoryBot::Internal.register_sequence(
FactoryBot::Sequence.new(:email, 1) { |n| "foo#{n}" }, FactoryBot::Sequence.new(:email, 1) { |n| "foo#{n}" }
) )
end end
end end
@ -60,6 +61,6 @@ describe FactoryBot::Attribute::Dynamic do
end end
describe FactoryBot::Attribute::Dynamic, "with a string name" do describe FactoryBot::Attribute::Dynamic, "with a string name" do
subject { FactoryBot::Attribute::Dynamic.new("name", false, -> {}) } subject { FactoryBot::Attribute::Dynamic.new("name", false, -> {}) }
its(:name) { should eq :name } its(:name) { should eq :name }
end end

View File

@ -1,10 +1,10 @@
describe FactoryBot::Attribute::Sequence do describe FactoryBot::Attribute::Sequence do
let(:sequence_name) { :name } let(:sequence_name) { :name }
let(:name) { :first_name } let(:name) { :first_name }
let(:sequence) { FactoryBot::Sequence.new(sequence_name, 5) { |n| "Name #{n}" } } let(:sequence) { FactoryBot::Sequence.new(sequence_name, 5) { |n| "Name #{n}" } }
subject { FactoryBot::Attribute::Sequence.new(name, sequence_name, false) } subject { FactoryBot::Attribute::Sequence.new(name, sequence_name, false) }
before { FactoryBot::Internal.register_sequence(sequence) } before { FactoryBot::Internal.register_sequence(sequence) }
its(:name) { should eq name } its(:name) { should eq name }

View File

@ -30,11 +30,11 @@ describe FactoryBot::AttributeList, "#define_attribute" do
attribute = double(:attribute, name: :attribute_name) attribute = double(:attribute, name: :attribute_name)
list = FactoryBot::AttributeList.new list = FactoryBot::AttributeList.new
expect do expect {
2.times { list.define_attribute(attribute) } 2.times { list.define_attribute(attribute) }
end.to raise_error( }.to raise_error(
FactoryBot::AttributeDefinitionError, FactoryBot::AttributeDefinitionError,
"Attribute already defined: attribute_name", "Attribute already defined: attribute_name"
) )
end end
end end
@ -44,11 +44,11 @@ describe FactoryBot::AttributeList, "#define_attribute with a named attribute li
association_with_same_name = FactoryBot::Attribute::Association.new(:author, :author, {}) association_with_same_name = FactoryBot::Attribute::Association.new(:author, :author, {})
list = FactoryBot::AttributeList.new(:author) list = FactoryBot::AttributeList.new(:author)
expect do expect {
list.define_attribute(association_with_same_name) list.define_attribute(association_with_same_name)
end.to raise_error( }.to raise_error(
FactoryBot::AssociationDefinitionError, FactoryBot::AssociationDefinitionError,
"Self-referencing association 'author' in 'author'", "Self-referencing association 'author' in 'author'"
) )
end end
@ -81,7 +81,7 @@ describe FactoryBot::AttributeList, "#associations" do
email_attribute = FactoryBot::Attribute::Dynamic.new( email_attribute = FactoryBot::Attribute::Dynamic.new(
:email, :email,
false, false,
->(u) { "#{u.full_name}@example.com" }, ->(u) { "#{u.full_name}@example.com" }
) )
author_attribute = FactoryBot::Attribute::Association.new(:author, :user, {}) author_attribute = FactoryBot::Attribute::Association.new(:author, :user, {})
profile_attribute = FactoryBot::Attribute::Association.new(:profile, :profile, {}) profile_attribute = FactoryBot::Attribute::Association.new(:profile, :profile, {})
@ -105,7 +105,7 @@ describe FactoryBot::AttributeList, "filter based on ignored attributes" do
it "filters #ignored attributes" do it "filters #ignored attributes" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:comments_count), build_ignored_attribute(:comments_count),
build_non_ignored_attribute(:email), build_non_ignored_attribute(:email)
) )
expect(list.ignored.names).to eq [:comments_count] expect(list.ignored.names).to eq [:comments_count]
@ -114,7 +114,7 @@ describe FactoryBot::AttributeList, "filter based on ignored attributes" do
it "filters #non_ignored attributes" do it "filters #non_ignored attributes" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:comments_count), build_ignored_attribute(:comments_count),
build_non_ignored_attribute(:email), build_non_ignored_attribute(:email)
) )
expect(list.non_ignored.names).to eq [:email] expect(list.non_ignored.names).to eq [:email]
@ -140,7 +140,7 @@ describe FactoryBot::AttributeList, "generating names" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:comments_count), build_ignored_attribute(:comments_count),
build_non_ignored_attribute(:last_name), build_non_ignored_attribute(:last_name),
build_association(:avatar), build_association(:avatar)
) )
expect(list.names).to eq [:comments_count, :last_name, :avatar] expect(list.names).to eq [:comments_count, :last_name, :avatar]
@ -150,7 +150,7 @@ describe FactoryBot::AttributeList, "generating names" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:posts_count), build_ignored_attribute(:posts_count),
build_non_ignored_attribute(:last_name), build_non_ignored_attribute(:last_name),
build_association(:avatar), build_association(:avatar)
) )
expect(list.ignored.names).to eq [:posts_count] expect(list.ignored.names).to eq [:posts_count]
@ -160,7 +160,7 @@ describe FactoryBot::AttributeList, "generating names" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:posts_count), build_ignored_attribute(:posts_count),
build_non_ignored_attribute(:last_name), build_non_ignored_attribute(:last_name),
build_association(:avatar), build_association(:avatar)
) )
expect(list.non_ignored.names).to eq [:last_name, :avatar] expect(list.non_ignored.names).to eq [:last_name, :avatar]
@ -170,7 +170,7 @@ describe FactoryBot::AttributeList, "generating names" do
list = build_attribute_list( list = build_attribute_list(
build_ignored_attribute(:posts_count), build_ignored_attribute(:posts_count),
build_non_ignored_attribute(:last_name), build_non_ignored_attribute(:last_name),
build_association(:avatar), build_association(:avatar)
) )
expect(list.associations.names).to eq [:avatar] expect(list.associations.names).to eq [:avatar]

View File

@ -1,7 +1,7 @@
describe FactoryBot::Decorator::AttributeHash do describe FactoryBot::Decorator::AttributeHash do
describe "#attributes" do describe "#attributes" do
it "returns a hash of attributes" do it "returns a hash of attributes" do
attributes = { attribute_1: :value, attribute_2: :value } attributes = {attribute_1: :value, attribute_2: :value}
component = double(:component, attributes) component = double(:component, attributes)
decorator = described_class.new(component, [:attribute_1, :attribute_2]) decorator = described_class.new(component, [:attribute_1, :attribute_2])
@ -11,7 +11,7 @@ describe FactoryBot::Decorator::AttributeHash do
context "with an attribute called 'attributes'" do context "with an attribute called 'attributes'" do
it "does not call itself recursively" do it "does not call itself recursively" do
attributes = { attributes: :value } attributes = {attributes: :value}
component = double(:component, attributes) component = double(:component, attributes)
decorator = described_class.new(component, [:attributes]) decorator = described_class.new(component, [:attributes])

View File

@ -5,8 +5,8 @@ describe FactoryBot::DefinitionProxy, "#add_attribute" do
attribute_value = -> { "dynamic attribute" } attribute_value = -> { "dynamic attribute" }
proxy.add_attribute(:attribute_name, &attribute_value) proxy.add_attribute(:attribute_name, &attribute_value)
expect(definition).to have_dynamic_declaration(:attribute_name). expect(definition).to have_dynamic_declaration(:attribute_name)
with_value(attribute_value) .with_value(attribute_value)
end end
it "declares a dynamic attribute on the factory when the proxy ignores attributes" do it "declares a dynamic attribute on the factory when the proxy ignores attributes" do
@ -14,9 +14,9 @@ describe FactoryBot::DefinitionProxy, "#add_attribute" do
proxy = FactoryBot::DefinitionProxy.new(definition, true) proxy = FactoryBot::DefinitionProxy.new(definition, true)
attribute_value = -> { "dynamic attribute" } attribute_value = -> { "dynamic attribute" }
proxy.add_attribute(:attribute_name, &attribute_value) proxy.add_attribute(:attribute_name, &attribute_value)
expect(definition).to have_dynamic_declaration(:attribute_name). expect(definition).to have_dynamic_declaration(:attribute_name)
ignored. .ignored
with_value(attribute_value) .with_value(attribute_value)
end end
end end
@ -29,9 +29,9 @@ describe FactoryBot::DefinitionProxy, "#transient" do
add_attribute(:attribute_name, &attribute_value) add_attribute(:attribute_name, &attribute_value)
end end
expect(definition).to have_dynamic_declaration(:attribute_name). expect(definition).to have_dynamic_declaration(:attribute_name)
ignored. .ignored
with_value(attribute_value) .with_value(attribute_value)
end end
end end
@ -49,8 +49,8 @@ describe FactoryBot::DefinitionProxy, "#method_missing" do
proxy = FactoryBot::DefinitionProxy.new(definition) proxy = FactoryBot::DefinitionProxy.new(definition)
proxy.author factory: :user proxy.author factory: :user
expect(definition).to have_association_declaration(:author). expect(definition).to have_association_declaration(:author)
with_options(factory: :user) .with_options(factory: :user)
end end
it "declares a dynamic attribute when called with a block" do it "declares a dynamic attribute when called with a block" do
@ -59,8 +59,8 @@ describe FactoryBot::DefinitionProxy, "#method_missing" do
attribute_value = -> { "dynamic attribute" } attribute_value = -> { "dynamic attribute" }
proxy.attribute_name(&attribute_value) proxy.attribute_name(&attribute_value)
expect(definition).to have_dynamic_declaration(:attribute_name). expect(definition).to have_dynamic_declaration(:attribute_name)
with_value(attribute_value) .with_value(attribute_value)
end end
it "raises a NoMethodError when called with a static-attribute-like argument" do it "raises a NoMethodError when called with a static-attribute-like argument" do
@ -71,7 +71,7 @@ describe FactoryBot::DefinitionProxy, "#method_missing" do
expect(invalid_call).to raise_error( expect(invalid_call).to raise_error(
NoMethodError, NoMethodError,
"undefined method 'static_attributes_are_gone' in 'broken' factory\n" \ "undefined method 'static_attributes_are_gone' in 'broken' factory\n" \
"Did you mean? 'static_attributes_are_gone { \"true\" }'\n", "Did you mean? 'static_attributes_are_gone { \"true\" }'\n"
) )
end end
end end
@ -98,18 +98,18 @@ describe FactoryBot::DefinitionProxy, "#sequence" do
proxy.sequence(:sequence, override) proxy.sequence(:sequence, override)
expect(FactoryBot::Sequence).to have_received(:new). expect(FactoryBot::Sequence).to have_received(:new)
with(:sequence, override) .with(:sequence, override)
end end
it "creates a new sequence with a block" do it "creates a new sequence with a block" do
allow(FactoryBot::Sequence).to receive(:new).and_call_original allow(FactoryBot::Sequence).to receive(:new).and_call_original
sequence_block = Proc.new { |n| "user+#{n}@example.com" } sequence_block = proc { |n| "user+#{n}@example.com" }
proxy = build_proxy(:factory) proxy = build_proxy(:factory)
proxy.sequence(:sequence, 1, &sequence_block) proxy.sequence(:sequence, 1, &sequence_block)
expect(FactoryBot::Sequence).to have_received(:new). expect(FactoryBot::Sequence).to have_received(:new)
with(:sequence, 1, &sequence_block) .with(:sequence, 1, &sequence_block)
end end
end end
@ -129,18 +129,18 @@ describe FactoryBot::DefinitionProxy, "#association" do
proxy.association(:association_name, name: "Awesome") proxy.association(:association_name, name: "Awesome")
expect(definition).to have_association_declaration(:association_name). expect(definition).to have_association_declaration(:association_name)
with_options(name: "Awesome") .with_options(name: "Awesome")
end end
it "when passing a block raises an error" do it "when passing a block raises an error" do
definition = FactoryBot::Definition.new(:post) definition = FactoryBot::Definition.new(:post)
proxy = FactoryBot::DefinitionProxy.new(definition) proxy = FactoryBot::DefinitionProxy.new(definition)
expect { proxy.association(:author) {} }. expect { proxy.association(:author) {} }
to raise_error( .to raise_error(
FactoryBot::AssociationDefinitionError, FactoryBot::AssociationDefinitionError,
"Unexpected block passed to 'author' association in 'post' factory", "Unexpected block passed to 'author' association in 'post' factory"
) )
end end
end end
@ -234,7 +234,7 @@ describe FactoryBot::DefinitionProxy, "#factory" do
proxy = FactoryBot::DefinitionProxy.new(definition) proxy = FactoryBot::DefinitionProxy.new(definition)
proxy.factory(:child, awesome: true) proxy.factory(:child, awesome: true)
expect(proxy.child_factories).to include([:child, { awesome: true }, nil]) expect(proxy.child_factories).to include([:child, {awesome: true}, nil])
end end
it "with a block" do it "with a block" do
@ -251,7 +251,7 @@ describe FactoryBot::DefinitionProxy, "#trait" do
it "declares a trait" do it "declares a trait" do
definition = FactoryBot::Definition.new(:name) definition = FactoryBot::Definition.new(:name)
proxy = FactoryBot::DefinitionProxy.new(definition) proxy = FactoryBot::DefinitionProxy.new(definition)
male_trait = Proc.new { gender { "Male" } } male_trait = proc { gender { "Male" } }
proxy.trait(:male, &male_trait) proxy.trait(:male, &male_trait)
expect(definition).to have_trait(:male).with_block(male_trait) expect(definition).to have_trait(:male).with_block(male_trait)
@ -262,7 +262,7 @@ describe FactoryBot::DefinitionProxy, "#initialize_with" do
it "defines the constructor on the definition" do it "defines the constructor on the definition" do
definition = FactoryBot::Definition.new(:name) definition = FactoryBot::Definition.new(:name)
proxy = FactoryBot::DefinitionProxy.new(definition) proxy = FactoryBot::DefinitionProxy.new(definition)
constructor = Proc.new { Array.new } constructor = proc { [] }
proxy.initialize_with(&constructor) proxy.initialize_with(&constructor)
expect(definition.constructor).to eq constructor expect(definition.constructor).to eq constructor

View File

@ -13,7 +13,7 @@ describe FactoryBot::Decorator::DisallowsDuplicatesRegistry do
decorator = FactoryBot::Decorator::DisallowsDuplicatesRegistry.new(registry) decorator = FactoryBot::Decorator::DisallowsDuplicatesRegistry.new(registry)
allow(registry).to receive(:registered?).and_return true allow(registry).to receive(:registered?).and_return true
expect { decorator.register(:same_name, {}) }. expect { decorator.register(:same_name, {}) }
to raise_error(FactoryBot::DuplicateDefinitionError, "Great thing already registered: same_name") .to raise_error(FactoryBot::DuplicateDefinitionError, "Great thing already registered: same_name")
end end
end end

View File

@ -22,10 +22,10 @@ describe FactoryBot::EvaluatorClassDefiner do
it "only instance_execs the block once even when returning nil" do it "only instance_execs the block once even when returning nil" do
count = 0 count = 0
attribute = stub_attribute :attribute do attribute = stub_attribute(:attribute) {
count += 1 count += 1
nil nil
end }
evaluator = define_evaluator(attributes: [attribute]) evaluator = define_evaluator(attributes: [attribute])
2.times { evaluator.attribute } 2.times { evaluator.attribute }
@ -47,7 +47,7 @@ describe FactoryBot::EvaluatorClassDefiner do
child_attributes = [stub_attribute, stub_attribute] child_attributes = [stub_attribute, stub_attribute]
child_evaluator = define_evaluator( child_evaluator = define_evaluator(
attributes: child_attributes, attributes: child_attributes,
parent_class: parent_evaluator_class, parent_class: parent_evaluator_class
) )
expect(child_evaluator.attribute_lists).to eq [parent_attributes, child_attributes] expect(child_evaluator.attribute_lists).to eq [parent_attributes, child_attributes]
@ -62,7 +62,7 @@ describe FactoryBot::EvaluatorClassDefiner do
def define_evaluator_class(arguments = {}) def define_evaluator_class(arguments = {})
evaluator_class_definer = FactoryBot::EvaluatorClassDefiner.new( evaluator_class_definer = FactoryBot::EvaluatorClassDefiner.new(
arguments[:attributes] || [], arguments[:attributes] || [],
arguments[:parent_class] || FactoryBot::Evaluator, arguments[:parent_class] || FactoryBot::Evaluator
) )
evaluator_class_definer.evaluator_class evaluator_class_definer.evaluator_class
end end

View File

@ -1,6 +1,6 @@
describe FactoryBot::Factory do describe FactoryBot::Factory do
it "has a factory name" do it "has a factory name" do
name = :user name = :user
factory = FactoryBot::Factory.new(name) factory = FactoryBot::Factory.new(name)
FactoryBot::Internal.register_factory(factory) FactoryBot::Internal.register_factory(factory)
@ -31,7 +31,7 @@ describe FactoryBot::Factory do
it "includes associations from the parent factory" do it "includes associations from the parent factory" do
association_on_parent = FactoryBot::Declaration::Association.new(:association_on_parent, {}) association_on_parent = FactoryBot::Declaration::Association.new(:association_on_parent, {})
association_on_child = FactoryBot::Declaration::Association.new(:association_on_child, {}) association_on_child = FactoryBot::Declaration::Association.new(:association_on_child, {})
define_class("Post") define_class("Post")
factory = FactoryBot::Factory.new(:post) factory = FactoryBot::Factory.new(:post)
@ -48,7 +48,7 @@ describe FactoryBot::Factory do
it "returns the overridden value in the generated attributes" do it "returns the overridden value in the generated attributes" do
name = :name name = :name
value = "The price is right!" value = "The price is right!"
hash = { name => value } hash = {name => value}
define_class("Name") define_class("Name")
factory = FactoryBot::Factory.new(name) factory = FactoryBot::Factory.new(name)
declaration = declaration =
@ -67,7 +67,7 @@ describe FactoryBot::Factory do
declaration = declaration =
FactoryBot::Declaration::Dynamic.new(name, false, -> { flunk }) FactoryBot::Declaration::Dynamic.new(name, false, -> { flunk })
factory.declare_attribute(declaration) factory.declare_attribute(declaration)
hash = { name.to_s => value } hash = {name.to_s => value}
result = factory.run(FactoryBot::Strategy::AttributesFor, hash) result = factory.run(FactoryBot::Strategy::AttributesFor, hash)
expect(result[name]).to eq value expect(result[name]).to eq value
@ -88,7 +88,7 @@ describe FactoryBot::Factory do
FactoryBot.aliases << [/(.*)_alias/, '\1'] FactoryBot.aliases << [/(.*)_alias/, '\1']
result = factory.run( result = factory.run(
FactoryBot::Strategy::AttributesFor, FactoryBot::Strategy::AttributesFor,
test_alias: "new", test_alias: "new"
) )
expect(result[:test_alias]).to eq "new" expect(result[:test_alias]).to eq "new"
@ -107,7 +107,7 @@ describe FactoryBot::Factory do
FactoryBot.aliases << [/(.*)_alias/, '\1'] FactoryBot.aliases << [/(.*)_alias/, '\1']
result = factory.run( result = factory.run(
FactoryBot::Strategy::AttributesFor, FactoryBot::Strategy::AttributesFor,
test_alias: "new", test_alias: "new"
) )
expect(result[:test]).to be_nil expect(result[:test]).to be_nil
@ -135,7 +135,7 @@ describe FactoryBot::Factory do
end end
it "creates a new factory while overriding the parent class" do it "creates a new factory while overriding the parent class" do
name = :user name = :user
define_class("User") define_class("User")
factory = FactoryBot::Factory.new(name) factory = FactoryBot::Factory.new(name)
FactoryBot::Internal.register_factory(factory) FactoryBot::Internal.register_factory(factory)
@ -296,8 +296,8 @@ describe FactoryBot::Factory, "running a factory" do
declaration = FactoryBot::Declaration::Dynamic.new(:name, false, -> { "value" }) declaration = FactoryBot::Declaration::Dynamic.new(:name, false, -> { "value" })
strategy = double("strategy", result: "result", add_observer: true) strategy = double("strategy", result: "result", add_observer: true)
define_model("User", name: :string) define_model("User", name: :string)
allow(FactoryBot::Declaration::Dynamic).to receive(:new). allow(FactoryBot::Declaration::Dynamic).to receive(:new)
and_return declaration .and_return declaration
allow(declaration).to receive(:to_attributes).and_return attributes allow(declaration).to receive(:to_attributes).and_return attributes
allow(FactoryBot::Strategy::Build).to receive(:new).and_return strategy allow(FactoryBot::Strategy::Build).to receive(:new).and_return strategy
factory = FactoryBot::Factory.new(:user) factory = FactoryBot::Factory.new(:user)

View File

@ -49,7 +49,7 @@ describe "definition loading" do
end end
end end
%w(spec test).each do |dir| %w[spec test].each do |dir|
describe "with a factories file under #{dir}" do describe "with a factories file under #{dir}" do
in_directory_with_files File.join(dir, "factories.rb") in_directory_with_files File.join(dir, "factories.rb")
it_should_behave_like "finds definitions" do it_should_behave_like "finds definitions" do
@ -66,7 +66,7 @@ describe "definition loading" do
describe "with several factories files under #{dir}/factories" do describe "with several factories files under #{dir}/factories" do
in_directory_with_files File.join(dir, "factories", "post_factory.rb"), in_directory_with_files File.join(dir, "factories", "post_factory.rb"),
File.join(dir, "factories", "person_factory.rb") File.join(dir, "factories", "person_factory.rb")
it_should_behave_like "finds definitions" do it_should_behave_like "finds definitions" do
it { should load_definitions_from("#{dir}/factories/post_factory.rb") } it { should load_definitions_from("#{dir}/factories/post_factory.rb") }
it { should load_definitions_from("#{dir}/factories/person_factory.rb") } it { should load_definitions_from("#{dir}/factories/person_factory.rb") }
@ -75,7 +75,7 @@ describe "definition loading" do
describe "with several factories files under #{dir}/factories in non-alphabetical order" do describe "with several factories files under #{dir}/factories in non-alphabetical order" do
in_directory_with_files File.join(dir, "factories", "b.rb"), in_directory_with_files File.join(dir, "factories", "b.rb"),
File.join(dir, "factories", "a.rb") File.join(dir, "factories", "a.rb")
it "loads the files in the right order" do it "loads the files in the right order" do
allow(FactoryBot).to receive(:load) allow(FactoryBot).to receive(:load)
wd = File.dirname(__FILE__) wd = File.dirname(__FILE__)
@ -91,8 +91,8 @@ describe "definition loading" do
describe "with nested and unnested factories files under #{dir}" do describe "with nested and unnested factories files under #{dir}" do
in_directory_with_files File.join(dir, "factories.rb"), in_directory_with_files File.join(dir, "factories.rb"),
File.join(dir, "factories", "post_factory.rb"), File.join(dir, "factories", "post_factory.rb"),
File.join(dir, "factories", "person_factory.rb") File.join(dir, "factories", "person_factory.rb")
it_should_behave_like "finds definitions" do it_should_behave_like "finds definitions" do
it { should load_definitions_from("#{dir}/factories.rb") } 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/post_factory.rb") }
@ -102,7 +102,7 @@ describe "definition loading" do
describe "with deeply nested factory files under #{dir}" do describe "with deeply nested factory files under #{dir}" do
in_directory_with_files File.join(dir, "factories", "subdirectory", "post_factory.rb"), in_directory_with_files File.join(dir, "factories", "subdirectory", "post_factory.rb"),
File.join(dir, "factories", "subdirectory", "person_factory.rb") File.join(dir, "factories", "subdirectory", "person_factory.rb")
it_should_behave_like "finds definitions" do 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/post_factory.rb") }
it { should load_definitions_from("#{dir}/factories/subdirectory/person_factory.rb") } it { should load_definitions_from("#{dir}/factories/subdirectory/person_factory.rb") }

View File

@ -4,10 +4,10 @@ describe FactoryBot::Internal do
trait = FactoryBot::Trait.new(:admin) trait = FactoryBot::Trait.new(:admin)
configuration = FactoryBot::Internal.configuration configuration = FactoryBot::Internal.configuration
expect { FactoryBot::Internal.register_trait(trait) }. expect { FactoryBot::Internal.register_trait(trait) }
to change { configuration.traits.count }. .to change { configuration.traits.count }
from(0). .from(0)
to(1) .to(1)
end end
it "returns the registered trait" do it "returns the registered trait" do
@ -31,10 +31,10 @@ describe FactoryBot::Internal do
sequence = FactoryBot::Sequence.new(:email) sequence = FactoryBot::Sequence.new(:email)
configuration = FactoryBot::Internal.configuration configuration = FactoryBot::Internal.configuration
expect { FactoryBot::Internal.register_sequence(sequence) }. expect { FactoryBot::Internal.register_sequence(sequence) }
to change { configuration.sequences.count }. .to change { configuration.sequences.count }
from(0). .from(0)
to(1) .to(1)
end end
it "returns the registered sequence" do it "returns the registered sequence" do
@ -75,10 +75,10 @@ describe FactoryBot::Internal do
factory = FactoryBot::Factory.new(:object) factory = FactoryBot::Factory.new(:object)
configuration = FactoryBot::Internal.configuration configuration = FactoryBot::Internal.configuration
expect { FactoryBot::Internal.register_factory(factory) }. expect { FactoryBot::Internal.register_factory(factory) }
to change { configuration.factories.count }. .to change { configuration.factories.count }
from(0). .from(0)
to(1) .to(1)
end end
it "returns the registered factory" do it "returns the registered factory" do
@ -101,10 +101,10 @@ describe FactoryBot::Internal do
it "registers the provided factory" do it "registers the provided factory" do
factory = FactoryBot::Factory.new(:object) factory = FactoryBot::Factory.new(:object)
configuration = FactoryBot::Internal.configuration configuration = FactoryBot::Internal.configuration
expect { FactoryBot::Internal.register_factory(factory) }. expect { FactoryBot::Internal.register_factory(factory) }
to change { configuration.factories.count }. .to change { configuration.factories.count }
from(0). .from(0)
to(1) .to(1)
end end
it "returns the registered factory" do it "returns the registered factory" do
@ -125,19 +125,19 @@ describe FactoryBot::Internal do
it "register the provided strategy name with the class" do it "register the provided strategy name with the class" do
configuration = FactoryBot::Internal.configuration configuration = FactoryBot::Internal.configuration
initial_strategies_count = configuration.strategies.count initial_strategies_count = configuration.strategies.count
expect do expect {
FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class) FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class)
end.to change { configuration.strategies.count }. }.to change { configuration.strategies.count }
from(initial_strategies_count). .from(initial_strategies_count)
to(initial_strategies_count + 1) .to(initial_strategies_count + 1)
end end
end end
describe ".strategy_by_name" do describe ".strategy_by_name" do
it "finds a registered strategy" do it "finds a registered strategy" do
FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class) FactoryBot::Internal.register_strategy(:strategy_name, :strategy_class)
expect(FactoryBot::Internal.strategy_by_name(:strategy_name)). expect(FactoryBot::Internal.strategy_by_name(:strategy_name))
to eq :strategy_class .to eq :strategy_class
end end
end end
end end

View File

@ -24,8 +24,8 @@ describe FactoryBot::Registry do
it "raises when an object cannot be found" do it "raises when an object cannot be found" do
registry = FactoryBot::Registry.new("Great thing") registry = FactoryBot::Registry.new("Great thing")
expect { registry.find(:object_name) }. expect { registry.find(:object_name) }
to raise_error(KeyError, "Great thing not registered: \"object_name\"") .to raise_error(KeyError, "Great thing not registered: \"object_name\"")
end end
it "adds and returns the object registered" do it "adds and returns the object registered" do

View File

@ -1,5 +1,5 @@
shared_examples "a sequence" do |options| shared_examples "a sequence" do |options|
first_value = options[:first_value] first_value = options[:first_value]
second_value = options[:second_value] second_value = options[:second_value]
it "has a next value equal to its first value" do it "has a next value equal to its first value" do
@ -23,9 +23,9 @@ end
describe FactoryBot::Sequence do describe FactoryBot::Sequence do
describe "a basic sequence" do describe "a basic sequence" do
let(:name) { :test } let(:name) { :test }
subject { FactoryBot::Sequence.new(name) { |n| "=#{n}" } } subject { FactoryBot::Sequence.new(name) { |n| "=#{n}" } }
its(:name) { should eq name } its(:name) { should eq name }
its(:names) { should eq [name] } its(:names) { should eq [name] }
it_behaves_like "a sequence", first_value: "=1", second_value: "=2" it_behaves_like "a sequence", first_value: "=1", second_value: "=2"
@ -46,9 +46,9 @@ describe FactoryBot::Sequence do
it "has the expected names as its names" do it "has the expected names as its names" do
names = [:foo, :bar, :baz] names = [:foo, :bar, :baz]
sequence = FactoryBot::Sequence.new(names.first, aliases: names.last(2)) do sequence = FactoryBot::Sequence.new(names.first, aliases: names.last(2)) {
"=#{n}" "=#{n}"
end }
expect(sequence.names).to eq names expect(sequence.names).to eq names
end end
@ -65,9 +65,9 @@ describe FactoryBot::Sequence do
it "has the expected names as its names" do it "has the expected names as its names" do
names = [:foo, :bar, :baz] names = [:foo, :bar, :baz]
sequence = FactoryBot::Sequence.new(names.first, 3, aliases: names.last(2)) do sequence = FactoryBot::Sequence.new(names.first, 3, aliases: names.last(2)) {
"=#{n}" "=#{n}"
end }
expect(sequence.names).to eq names expect(sequence.names).to eq names
end end

View File

@ -1,5 +1,5 @@
describe FactoryBot::Strategy::AttributesFor do describe FactoryBot::Strategy::AttributesFor do
let(:result) { { name: "John Doe", gender: "Male", admin: false } } let(:result) { {name: "John Doe", gender: "Male", admin: false} }
let(:evaluation) { double("evaluation", hash: result) } let(:evaluation) { double("evaluation", hash: result) }
it_should_behave_like "strategy without association support" it_should_behave_like "strategy without association support"
@ -9,8 +9,8 @@ describe FactoryBot::Strategy::AttributesFor do
end end
it "does not run the to_create block" do it "does not run the to_create block" do
expect do expect {
subject.result(evaluation) subject.result(evaluation)
end.to_not raise_error }.to_not raise_error
end end
end end

View File

@ -7,7 +7,7 @@ describe FactoryBot::Strategy::Create do
"evaluation", "evaluation",
object: nil, object: nil,
notify: nil, notify: nil,
create: nil, create: nil
) )
subject.result(evaluation) subject.result(evaluation)

View File

@ -11,7 +11,7 @@ shared_examples "disabled persistence method" do |method_name|
it "raises an informative error if the method is called" do it "raises an informative error if the method is called" do
expect { instance.send(method_name) }.to raise_error( expect { instance.send(method_name) }.to raise_error(
RuntimeError, RuntimeError,
"stubbed models are not allowed to access the database - #{instance.class}##{method_name}()", "stubbed models are not allowed to access the database - #{instance.class}##{method_name}()"
) )
end end
end end
@ -24,9 +24,9 @@ describe FactoryBot::Strategy::Stub do
context "asking for a result" do context "asking for a result" do
let(:result_instance) do let(:result_instance) do
define_class("ResultInstance") do define_class("ResultInstance") {
attr_accessor :id, :created_at attr_accessor :id, :created_at
end.new }.new
end end
let(:evaluation) do let(:evaluation) do

View File

@ -1,8 +1,8 @@
describe FactoryBot do describe FactoryBot do
it "finds a registered strategy" do it "finds a registered strategy" do
FactoryBot.register_strategy(:strategy_name, :strategy_class) FactoryBot.register_strategy(:strategy_name, :strategy_class)
expect(FactoryBot.strategy_by_name(:strategy_name)). expect(FactoryBot.strategy_by_name(:strategy_name))
to eq :strategy_class .to eq :strategy_class
end end
describe ".use_parent_strategy" do describe ".use_parent_strategy" do

View File

@ -39,9 +39,9 @@ module DefineConstantMacros
end end
def clear_generated_table(table_name) def clear_generated_table(table_name)
ActiveRecord::Base. ActiveRecord::Base
connection. .connection
execute("DROP TABLE IF EXISTS #{table_name}") .execute("DROP TABLE IF EXISTS #{table_name}")
end end
private private
@ -57,7 +57,7 @@ RSpec.configure do |config|
config.before(:all) do config.before(:all) do
ActiveRecord::Base.establish_connection( ActiveRecord::Base.establish_connection(
adapter: "sqlite3", adapter: "sqlite3",
database: ":memory:", database: ":memory:"
) )
end end

View File

@ -48,7 +48,7 @@ module DeclarationMatchers
def failure_message def failure_message
[ [
"expected declarations to include declaration of type #{@declaration_type}", "expected declarations to include declaration of type #{@declaration_type}",
@options ? "with options #{options}" : nil, @options ? "with options #{options}" : nil
].compact.join " " ].compact.join " "
end end
@ -56,8 +56,8 @@ module DeclarationMatchers
def expected_declaration def expected_declaration
case @declaration_type case @declaration_type
when :dynamic then FactoryBot::Declaration::Dynamic.new(@name, ignored?, @value) when :dynamic then FactoryBot::Declaration::Dynamic.new(@name, ignored?, @value)
when :implicit then FactoryBot::Declaration::Implicit.new(@name, @factory, ignored?) when :implicit then FactoryBot::Declaration::Implicit.new(@name, @factory, ignored?)
when :association when :association
if @options if @options
FactoryBot::Declaration::Association.new(@name, options) FactoryBot::Declaration::Association.new(@name, options)

View File

@ -1,5 +1,5 @@
shared_examples_for "strategy without association support" do shared_examples_for "strategy without association support" do
let(:factory) { double("associate_factory") } let(:factory) { double("associate_factory") }
let(:attribute) { FactoryBot::Attribute::Association.new(:user, :user, {}) } let(:attribute) { FactoryBot::Attribute::Association.new(:user, :user, {}) }
def association_named(name, overrides) def association_named(name, overrides)
@ -70,9 +70,9 @@ end
shared_examples_for "strategy with callbacks" do |*callback_names| shared_examples_for "strategy with callbacks" do |*callback_names|
let(:result_instance) do let(:result_instance) do
define_class("ResultInstance") do define_class("ResultInstance") {
attr_accessor :id attr_accessor :id
end.new }.new
end end
let(:evaluation) do let(:evaluation) do