Skip to content

Instantly share code, notes, and snippets.

@woods
Created December 10, 2014 22:34
Show Gist options
  • Save woods/898d7ada322810867526 to your computer and use it in GitHub Desktop.
Save woods/898d7ada322810867526 to your computer and use it in GitHub Desktop.
# Include this module into your fake models to get some helpful default functionality.
#
# Example usage:
#
# class AuxiliaryOfficer
# include FakeModel
#
# attr_accessor :name, :started_on, :comments
#
# def self.fake_attributes
# {
# name: Faker::Name.name,
# started_on: 1.year.ago.to_date,
# comments: Faker::Lorem.paragraph
# }
# end
#
# has_many :events
# belongs_to :user
# end
#
module FakeModel
extend ActiveSupport::Concern
included do
include ActiveModel::Model
extend ActiveModel::Callbacks
extend ActiveModel::Naming
attr_accessor :persisted
end
module ClassMethods
# Override this in your class to provide the default faker attributes
# for your class.
def fake_attributes
{}
end
# Generate one fake object of this class
def fake(params={})
new(fake_attributes.merge(params))
end
# Generate several fake objects of this class
def fakes(count=10, params={})
count.times.collect { fake(params) }
end
# Declare a belongs_to relationship that returns a fake of the other class
def belongs_to(attribute_name)
define_method attribute_name do
attribute_name.to_s.classify.constantize.fake
end
end
# Declare a has_many relationship that returns several fakes of the other class
def has_many(plural_attribute_name)
define_method plural_attribute_name do
plural_attribute_name.to_s.singularize.classify.constantize.fakes
end
end
end
# Assign this object's #persisted= method if you want to change this result
def persisted?
@persisted.nil? ? false : @persisted
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment