(1) Rails provides a tool for quickly generating sample data, called "firmware" by default. The firmware is a YAML-formatted file that can be used to generate sample data. For example:
Contacts.yml
Aaron:firstname: "Aaron" LastName: "Sumner" email: "[email protected]"
In the test you can refer to Contacts (: Aaron), you can get a contact, all attributes have values attached, but the firmware has drawbacks:
Data in the firmware can easily be corrupted
Rails skips data validation when the firmware is stored in the test library
(2) Use of pre-component factory girl, for example:
Spec/factories/contacts.rb
Factorygirl.define do factory:contact do FirstName "John" LastName "Doe" sequence (: email) {|n| " Johndoe#{n} @example. com "} endend
Use Factorygirl.create (: Contact) (Deposit database) Factorygirl.build (: Contact) (no database) in the test, sequence guaranteed n increment, each mailbox is different, can be used when there is unique authentication
At the same time the pre-component factory girl also has its own problems
Will slow down the test
Pre-components are poorly maintained when model correlation is complex
(3) Starting from Factory Girl 3.0, only a few configuration can be omitted to omit the pre-assembly call when the previous Factorygirl, configured as follows:
Spec/spec_helper.rb
Rspec.configure do |config| Config.include Factorygirl::syntax::methodsend
(4) The association in the pre-assembly, you can use the association method, it will tell Factorygirl, if the phone belongs to the contact person is not passed to the build method (or Create method), create a new contact
(5) Inheritance in the pre-component, the same attributes can be written in the top-level factory, while the different attributes are distinguished using nested factory, such as:
Factorygirl.define do factory:p hone do association:contact phone {' 123-555-1234 '} Factory:hom E_phone do phone_type ' home ' end Factory:work_phone does phone_type ' work ' end EndEnd
(6) Use Faker to generate more realistic data, such as:
Faker::P Honenumber.phone_number
Faker::name.first_name
Faker::name.last_name
Faker::internet.email
(7) There are also after callback functions in Factorygirl, for example:
Factorygirl.define do firstname {faker::name.first_name} lastname {Faker::name.last_name} email {faker::inte Rnet.email} after (: build) do |contact| [: Home_phone,: Work_phone,: Mobile_phone].each do |phone| Contact.phones << Factorygirl.build (:p hone, Phone_type:phone, contact:contact) End EndEnd
(8) If the test becomes slow, it is best to remove the pre-component association, manually add the required data or use a pure Ruby object to generate the data
Use of Factorygirl and Faker