Factory Girl is a tool dedicated to constructing simulated test data to perfectly replace fixture.
The disadvantage of fixture is obvious. It is often necessary to deal with various associations and dependencies. If the test requires a large amount of data, you must manually create the data yourself. These solutions are available in factory girl. Association can be used to generate a large amount of data to solve the association between objects. sequence can solve the problem of generating a large amount of test data.
Add factory girl
#Gemfilegroup :development, :test do gem 'factory_girl_rails'end
It is best to modify spec_helper.rb and comment out the fixture_path line to disable fixture.
# /spec/spec_helper.rb# config.fixture_path = "#{::Rails.root}/spec/fixtures"
Factory Girl usage principles
1. Each model defines a factory.
2. If the model is relatively small, put all factory definitions in a file spec/factories. RB.
If multiple models are copied, each model creates a file [model_names] S. Rb in the spec/factories/directory.
Three common expressions in rspec
User = Factory (: User) # equivalent to new + save! User = factory. Create (: User) # Same as above, is full write user = factory. Build (: User,: username => 'camel ') # Only new does not save
Example
# Spec/factories. rbfactorygirl. define do Factory: User do sequence (: email) {| n | "email # {n} @ factory.com"} password "888888" password_confirmation "888888" End Factory: post do title "hello" association: user # Association: Author,: factory =>: user # associates with another user and defines an alias. Endend
Call methods in rspec
post = Factory(:post)
In fact, the above Code is equivalent:
user = User.newuser.email = "test@example.com"user.save!post = Post.newpost.title = "Hello"post.user = userpost.save!
For more information, see: https://github.com/thoughtbot/factory_girl
> Original article. Please reprint it. Reprinted Please note: Reprinted from Ruby fans, thank you!
> Original article URL: summary of how factory girl works