FactoryGirl
2197 ワード
なぜfactoryを使うのかgirl
テストを書くとき、データを構築する必要があることがよくあります.作成するデータについては、次のようになります.
factory girlは、これらの問題を解決するために便利なメカニズムを提供しています.
factory_girlの使用
#
factory :user do
sequence(:email) { |n| "user-#{n}@example.com" }
end
# , Faker gem
factory :user do
sequence(:name) { Faker::Name::name }
end
#
FactoryGirl.create_list(:user, 2) # user
#
FactoryGirl.define do
factory :user do
email "[email protected]"
end
factory :post do
user
end
end
#
user = User.new
user.email = "[email protected]"
user.save!
post = Post.new
post.user = user
post.save!
#
FactoryGirl.define do
factory :post do
association :author, factory: :user
end
end
#
FactoryGirl.define do
factory :post do
name "post-name"
factory :post_with_comments do
after(:create) do |post, evaluator|
create_list(:comment, 5, post: post)
end
end
end
end
#
FactoryGirl.define do
factory :post do
name "post-name"
factory :post_with_comments do
transient do
comments_count 5
end
after(:create) do |post, evaluator|
create_list(:comment, evaluator.comments_count, post: post)
end
end
end
end
create(:post_with_comments, 2) # comments post
create(:post_with_comments, 2) # comments post