Gem: Factory Girl

intro

  • a library for setting up Ruby objects as test data.
  • factory_girl is a fixtures replacement with a straightforward definition syntax
  • build strategies (saved objs, unsaved objs, attribute hashes, and stubbed objs)
  • multiple factories, transient, lazy attributes, trait, inheritance
  • sequences, aliases, associations, callbacks, etc...

config in rails

  • add factory_girl_rails gem in development and test env
  • require 'factory_girl_rails' and 'support/factory_girl' to 'spec_helper'.

lazy attributes

  • 'normal' attributes are evaluated when the factory is defined.
  • 'lazy' attributes are evaluated when the instance is initialised.
  • tips: provide static values as 'normal' attributes, like name, description, etc.
  • tips: provide associations and dynamically created values as 'lazy' attrs, e.g. Time.
  • tips: 'lazy' attributes can work with 'transient' attributes.

play in rails console

  1. add factory_girl_rails gem in development and test env.
  2. rails console test --sandbox # go in console test env sandbox mode.
  3. include FactoryGirl::Syntax::Methods # call methods without FactoryGirl.
  4. user = build(:user) # initialize user instance from user factory.

check validation

  1. FactoryGirl.factories get all 'FactoryGirl::Factory' instances
  2. FactoryGirl.factories.each { |f| puts f.name } # show all factory names
  3. target_factories = FactoryGirl.factories.select { |f| f.name =~ /^user_/ }
  4. FactoryGirl.lint target_factories; # FactoryGirl.lint check all factories

Resources:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容