Coder Social home page Coder Social logo

famili's Introduction

Famili

Yet Another ObjectMother pattern implementation for rails testing

Why

We meet some problems with factory-girl:

  • We require quite complex logic for creation of test models

  • We require use factories with running rails application for integration tests

  • So why don’t make factory just another class in rails lib, and get extensibility of factories/mothers and rails lazy loading and dependency management?

Setup

  1. Create folder app/famili under project root

  2. Add app/famili to autoload path

# application.rb
config.autoload_paths.push 'app/famili'

Example

To define factory/mother for models User and Article just add following files to your app/famili directory:

#app/famili/user_famili.rb
class UserFamili < Famili::Mother
  fist_name { 'nicola' }
  last_name { 'nicola' }
  email     { "#{last_name}@mail.lv" } 

  def before_save(user)
      #...
  end

  def after_create(user)
      #...
  end
end

#app/famili/article_famili.rb
class ArticleFamili < Famili::Mother
  #creating association
  user  { UserFamili.create }
  title { "article by #{user.last_name}" }
end

And you can use it anywhere in tests or controllers:

UserFamili.create(:fist_name=>'Override') # create model
UserFamili.build(:fist_name=>'Override')  # build model (do not save)
UserFamili.build_hash(:fist_name=>'Override')   # get attributes hash

ArticleFamili.create #create article with user

Inheritance

You can inherite mothers just like plain ruby classes, Just think each declaration field_name {…} as method definition

class UserFamili < Famili::Mother
  name { "nicola" }
end

class PersonFamili < UserFamili
  email { "#{name}@emial.com" }
end

Mother methods

Mother have some usable methods, which can be used

class UserFamili < Famili::Mother
  last_name { 'nicola' }
  login { "#{last_name}_#{unique}" } 
  number { sequence_number }
end

Traits

You can add named set of attributes to override or extend default values

class UserFamili < Famili::Mother
  last_name { 'nicola' }
  login { "#{last_name}_#{unique}" }
  number { sequence_number }

  trait :unidentified do
    last_name { 'unknown' }
  end
end

UserFamili.unidentified.create(:first_name => 'john') # john unknown

Scopes

Its also possible to use named scopes (like ActiveRecord)

class UserFamili < Famili::Mother
  last_name { 'nicola' }

  scope :prefixed do |prefix|
    scoped(last_name: "#{prefix}#{attributes[:last_name]}")
  end

  scope :suffixed do |suffix|
    scoped(last_name: "#{attributes[:last_name]}#{suffix}")
  end

  scope :mr_junior do
    prefixed('Mr ').suffixed(', Jr')
  end
end

Anonymous scopes

shared = UserFamili.scoped(:first_name => 'jeffry')
shared.create(:last_name => 'stone') # jeffry stone
shared.create(:last_name => 'snow')  # jeffry snow

Associations

You can rewrite ArticleFamili declared above with using declarative association syntax:

class ArticleFamili < Famili::Mother
  has :user do
    last_name { 'Smith' }
  end
end

Collections

When you need to create number of similar objects, you can use {build,create}_brothers methods:

brothers = UserFamili.create_brothers(2, :first_name => 'john') # both john nicola, but with different login and number

If you have complex initialization logic, which you want apply just after object was initialized, you can do it in initialization block:

UserFamili.create do |user|
  user.login = "updated_#{user.login}"
end

Custom Persistence

You even can use famili for not active record models. You don’t need change everything if you just need to build object. But if you need custom persistence you may write custom save method:

class Person
  attr_accessor :persisted, :name
end

class PersonFamili < Famili::Mother
  name { 'John Smith' }

  def save(model)
      model.persisted = true
  end
end

Now, you can create your model as usual:

PersonFamili.create(name: 'Barry Redwell') # persisted == true

If you need some additional objects for persistence (a.e. you are using some persistence service), then you have option to use famili instance instead of singleton:

class XmlSerializer
  def serialize(model)
  end
end

class PersonFamili < Famili::Mother
  name { 'John Smith' }

  def initialize(serializer)
      @serializer = serializer
  end

  def save(person)
      serializer.serialize(person)
  end
end

and usage sample:

PersonFamili.new(XmlSerializer.new).create

Some useful methods

  • sequence_number - incremented with each instance

  • unique - just unique string

  • we a planing add more

Install

Put following lineinto your Gemfile

gem 'famili'

FEATURES

CHANGE LOG:

  • 1.1.0 - support custom persistence, support building & creating of objects using famili instance

  • 1.0.0 - changed API (old scope renamed to trait, scope conception refined)

  • 0.1.9 - optimize creation of relations

  • 0.1.8 - support brother index in brothers init block, fix bug with using same mother instance for all childs, support declarative association syntax (has :user)

  • 0.1.7 - fix build_hash result to not return updated_at and created_at (it caused errors in models created by new migrations in Rails 3.2)

  • 0.1.6 - support creation of models with properties which have only set accessors

  • 0.1.5 - fix method_missing in define_method

  • 0.1.4 - famili now creates child in scope of model. So, self is a reference to model.

  • 0.1.3 - supported anonym scopes with scoped. Supported collection creation methods: build_brothers, create_brothers. Supported initialization block for build, create, build_brothers, create_brothers.

  • 0.1.2 - migrated to Rails 3 and Ruby 1.9 (no backward compatibility). Supported scopes & access to model methods. Fixed multiple access to calculated properties.

  • 0.0.6 - rename Mother#hash to Mother#build_hash (to avoid conflicts with Object#hash in Ruby 1.9). Old name keeped as alias when using with oldest versions of Ruby for backward compatibility.

  • 0.0.5 - add raise NoMethodError if property declared without block (becose it is error-prone), fix Famili::Mother.class#name method

  • 0.0.3 - fix Mother.create call model.save!; Mother.hash return symbolized hash

  • 0.0.2 - add inheritance, and mother methods [unique,sequence_number]

  • 0.0.1 - created

TODO

  • generators

LICENSE:

(The MIT License)

Copyright © 2010 niquola

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

famili's People

Contributors

mirasrael avatar niquola avatar

Stargazers

 avatar Ilya avatar  avatar Mike Lapshin avatar

Watchers

Mike Lapshin avatar  avatar  avatar James Cloos avatar

famili's Issues

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.