- Author
- Version
-
0.0.4
A simple method for adding automatic fake record generation to Ruby on Rails via a plugin.
script/plugin install git://github.com/theworkinggroup/rails_model_faker.git
Adding support to an existing model is easy:
class MyModel < ActiveRecord::Base can_fake :name, :with => lambda { Faker::Name.name } end
An alternative syntax is to append a block to the can_fake call:
class MyModel < ActiveRecord::Base can_fake :name do Faker::Name.name end end
Multiple fields can also be faked with a single call:
class MyModel < ActiveRecord::Base can_fake :work_email, :home_email do Faker::Internet.email end end
Any related model can be faked without any special options:
class MyModel < ActiveRecord::Base belongs_to :account can_fake :account end
This also works for associations:
class MyModel < ActiveRecord::Base has_many :accounts end fake = MyModel.create_fake fake_account = fake.accounts.create_fake
Additionally, generic fake methods can be defined using an initalizer:
# config/initializers/faker.rb RailsModelFaker.config do # Define a simple company_name generator can_fake :company_name do Faker::Company.name end # The model class and the defined parameters are provided, # but do not need to be used. In this case it will push # in multiple parameters can_fake :full_name do |model_class, params| params[:first_name] = Faker::Name.first_name params[:last_name] = Faker::Name.last_name # If not intending to populate a specific field, return # the modified params. params end end
These module extensions can be used to simplify the definition of fakers:
class MyCompany < ActiveRecord::Base can_fake :name, :with => :company_name end
Once defined, a model class can be used to fake individual parameters:
MyCompany.fake(:name)
Using a fake-capable model is straightforward either by a direct call, or by an intermediate step:
# Prepare a fake model fake = MyModel.build_fake # Equivalent method using fake_params fake = MyModel.new(MyModel.fake_params) # Create an instance of a fake model fake = MyModel.create_fake # Equivalent method using fake_params fake = MyModel.create(MyModel.fake_params) # Create an instance of a fake model and throw exceptions on a # validation failure. fake = MyModel.create_fake! # Equivalent method using fake_params fake = MyModel.create!(MyModel.fake_params)
In all cases, options can be passed in to the various methods to seed the fake with some pre-defined data:
fake = MyModel.create_fake(:name => 'Test')
Any keys that are defined will not be re-populated.
All models can be interrogated as to their faking capability:
MyModel.can_fake?(:name) # => true
Copyright © 2009-2010 The Working Group (twg.ca/)