工厂女孩多重价值观
Factory girl multiple values
我知道我可以像这样给工厂女孩静态数据值:
factory :post do
title 'New post'
number 7
end
但是,如果我对每个标题和编号有多个值怎么办。如果标题是 'New Post'、'Old Post'、'Hello' 并且数字是 7、8、9 怎么办?我如何将这些数据传递给工厂女孩?我应该使用数组还是使用多个 do 结束块?
你可以简单地做:
posts_attrs = [{ title: 'new', number: 6}, { title: 'old' }]
posts_attrs.each do |post_attrs|
factory :post do
title post_attrs[:title] || 'default title'
number post_attrs[:number] || 1
end
end
如果您想将值作为参数传递:
factory :post do
title 'Default Title'
end
# create(:post, title: 'Custom Title')
如果您只想随机化值,那么只需:
factory :post do
title { ['New Post', 'Old Post', 'Hello'].sample }
end
对于数字,您可以使用 FactoryGirl 序列:
FactoryGirl.define do
sequence :email do |n|
"person#{n}@example.com"
end
end
要生成一些随机字符串,有 gem Faker
:
FactoryGirl.define do
factory :post do
title { Faker::Lorem.sentence }
end
end
Faker 可用于生成随机电子邮件、字符串、电子商务项目、地址和许多其他内容,请参阅 https://github.com/stympy/faker
我知道我可以像这样给工厂女孩静态数据值:
factory :post do
title 'New post'
number 7
end
但是,如果我对每个标题和编号有多个值怎么办。如果标题是 'New Post'、'Old Post'、'Hello' 并且数字是 7、8、9 怎么办?我如何将这些数据传递给工厂女孩?我应该使用数组还是使用多个 do 结束块?
你可以简单地做:
posts_attrs = [{ title: 'new', number: 6}, { title: 'old' }]
posts_attrs.each do |post_attrs|
factory :post do
title post_attrs[:title] || 'default title'
number post_attrs[:number] || 1
end
end
如果您想将值作为参数传递:
factory :post do title 'Default Title' end # create(:post, title: 'Custom Title')
如果您只想随机化值,那么只需:
factory :post do title { ['New Post', 'Old Post', 'Hello'].sample } end
对于数字,您可以使用 FactoryGirl 序列:
FactoryGirl.define do
sequence :email do |n|
"person#{n}@example.com"
end
end
要生成一些随机字符串,有 gem Faker
:
FactoryGirl.define do
factory :post do
title { Faker::Lorem.sentence }
end
end
Faker 可用于生成随机电子邮件、字符串、电子商务项目、地址和许多其他内容,请参阅 https://github.com/stympy/faker