module FactoryBot::Syntax::Methods
This module is a container for all strategy methods provided by FactoryBot. This includes all the default strategies provided ({Methods#build}, {Methods#create}, {Methods#build_stubbed}, and {Methods#attributes_for}), as well as the complementary *_list and *_pair methods. @example singular factory execution
# basic use case build(:completed_order) # factory yielding its result to a block create(:post) do |post| create(:comment, post: post) end # factory with attribute override attributes_for(:post, title: "I love Ruby!") # factory with traits and attribute override build_stubbed(:user, :admin, :male, name: "John Doe")
@example multiple factory execution
# basic use case build_list(:completed_order, 2) create_list(:completed_order, 2) # factory with attribute override attributes_for_list(:post, 4, title: "I love Ruby!") # factory with traits and attribute override build_stubbed_list(:user, 15, :admin, :male, name: "John Doe")
Public Instance Methods
Source
# File lib/factory_bot/syntax/methods.rb, line 120 def generate(*uri_parts, scope: nil) uri = FactoryBot::UriManager.build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || raise(KeyError, "Sequence not registered: #{FactoryBot::UriManager.build_uri(uri_parts)}") increment_sequence(sequence, scope: scope) end
Generates and returns the next value in a global or factory sequence.
Arguments:
context: (Array of Symbols) The definition context of the sequence, with the sequence name as the final entry scope: (object)(optional) The object the sequence should be evaluated within
Returns:
The next value in the sequence. (Object)
Example:
generate(:my_factory, :my_trair, :my_sequence)
Source
# File lib/factory_bot/syntax/methods.rb, line 144 def generate_list(*uri_parts, count, scope: nil) uri = FactoryBot::UriManager.build_uri(uri_parts) sequence = Sequence.find_by_uri(uri) || raise(KeyError, "Sequence not registered: '#{uri}'") (1..count).map do increment_sequence(sequence, scope: scope) end end
Generates and returns the list of values in a global or factory sequence.
Arguments:
uri_parts: (Array of Symbols) The definition context of the sequence, with the sequence name as the final entry scope: (object)(optional) The object the sequence should be evaluated within
Returns:
The next value in the sequence. (Object)
Example:
generate_list(:my_factory, :my_trair, :my_sequence, 5)
Private Instance Methods
Source
# File lib/factory_bot/syntax/methods.rb, line 169 def increment_sequence(sequence, scope: nil) value = sequence.next(scope) raise if value.respond_to?(:start_with?) && value.start_with?("#<FactoryBot::Declaration") value rescue raise ArgumentError, "Sequence '#{sequence.uri_manager.first}' failed to " \ "return a value. Perhaps it needs a scope to operate? (scope: <object>)" end
Increments the given sequence and returns the value.
Arguments:
sequence: The sequence instance scope: (object)(optional) The object the sequence should be evaluated within