Sha256: 4d70a54b6c746b3513d0b0fa2b4fb5c1ab1243e72a237b8d81e7819e765c49e4

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

module Factory
  # Build actions for the class
  def self.build(klass, &block)
    name = klass.to_s.underscore
    define_method("#{name}_attributes", block)
    
    module_eval <<-end_eval
      def valid_#{name}_attributes(attributes = {})
        #{name}_attributes(attributes)
        attributes
      end
      
      def new_#{name}(attributes = {})
        #{klass}.new(valid_#{name}_attributes(attributes))
      end
      
      def create_#{name}(*args)
        record = new_#{name}(*args)
        record.save!
        record.reload
        record
      end
    end_eval
  end
  
  build Email do |attributes|
    attributes[:sender] = create_user unless attributes.include?(:sender)
    attributes.reverse_merge!(
      :subject => 'New features',
      :body => 'Lots of new things to talk about... come to the meeting tonight to find out!'
    )
  end
  
  build EmailAddress do |attributes|
    attributes.reverse_merge!(
      :name => 'John Smith',
      :spec => 'john.smith@gmail.com'
    )
  end
  
  build MessageRecipient do |attributes|
    attributes[:message] = create_message unless attributes.include?(:message)
    attributes[:receiver] = create_user(:login => 'me') unless attributes.include?(:receiver)
    attributes.reverse_merge!(
      :kind => 'to'
    )
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
has_emails-0.1.0 test/factory.rb
has_emails-0.1.1 test/factory.rb