Gem: Factory Girl
2017-04-24 本文已影响42人
bookinstock_
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
- add factory_girl_rails gem in development and test env.
- rails console test --sandbox # go in console test env sandbox mode.
- include FactoryGirl::Syntax::Methods # call methods without FactoryGirl.
- user = build(:user) # initialize user instance from user factory.
check validation
- FactoryGirl.factories get all 'FactoryGirl::Factory' instances
- FactoryGirl.factories.each { |f| puts f.name } # show all factory names
- target_factories = FactoryGirl.factories.select { |f| f.name =~ /^user_/ }
- FactoryGirl.lint target_factories; # FactoryGirl.lint check all factories
Resources:
- Github: factory_girl, factory_girl_rails
- https://github.com/thoughtbot/factory_girl
- http://www.rubydoc.info/gems/factory_girl *
- http://stackoverflow.com/questions/tagged/factory-girl
- https://ruby-china.org/topics/3777
- https://ruby-china.org/topics/22003
- http://code.tutsplus.com/articles/factory-girl-101--cms-25087
- http://code.tutsplus.com/articles/factory-girl-201--cms-25171
- http://arjanvandergaag.nl/blog/factory_girl_tips.html