首页 > 其他 > 详细

Rails factory bot Document

时间:2019-10-10 15:51:28      阅读:122      评论:0      收藏:0      [点我收藏+]

创建: 2019/10/10

 

安装
 Gemfile  
# Gemfile
group :development, :test do
  gem ‘factory_bot_rails
end

 

 省略类名的设置

 

#spec/rails_helper.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

 

 文件位置

 

spec/factories/

 

   
使用
 定义factory

 

FactoryBot.define do
  factory :book do
    title { "factory sample" }
  end
  factory :sample, class: Book do
    title { "sample" }
  end
end

 

 生成数据

 

 方法  返回值  DB保存  DB保存(association)  id
 
build(factory[, attributes])

 attributes必须为存在的属性

 model实例  X  O  nil
 
build_stubbed(factory[, attributes])

 ● attributes必须为存在的属性

 model实例  X  X  合适的值
 
create(factory[, attributes])

 ● attributes必须为存在的属性

 model实例  O  O  DB保存的值
 
attributes_for(factory[, attributes])

 ● 只返回factory里指定的,没有指定的一律不返回

 ● attributes可以指定任意, 包括不存在的属性

 属性哈希  X  X  无

 

 批量生成

 

*_list(factory, count, attributes)

例:

books = create_list(:book, 10, price: 9999)

 

 序列

 sequence:

sequence :name do |i|
    ...
end

 generate:

factory :sample do
    attribute { generate :name }
end

 例: 

FactoryBot.define do
  sequence :isbn do |p|
    "UUID-#{11111*p}"
  end

  factory :book do
    title { "factory sample" }
    isbn { generate :isbn }
  end
end

 

 

 生成association

 (belongs_to)

 

association :关联名, factory: ...[, strategy: :build][, attributes]
 factory  如果与关联名相同则可以省略
 strategy

 生成使用的方法

 build/create/build_stubbed

 attributes

 指定覆盖的属性

 ● 只能用在belongs_to

 ● 也可以直接在belongs_to关系里放入factory  

FactoryBot.define do
  sequence :review_bodies do |i|
    "review-#{i}"
  end
  factory :review do
    body { generate :review_bodies }
    user
    book
  end
end

 

 

 给factory添加别名

 

factory :sample, class: User, aliases: [...] do
    ...
end

 

 使用固有词做属性

 

add_attribute(name) { ... }

 

 添加不是固有attribute的属性

 

transient do
    sample { "sample" }
    ...
end

例:

FactoryBot.define do
  sequence :review_bodies do |i|
    "review-#{i}"
  end
  factory :review do
    transient do
      comment { "" }
    end
    body { comment.blank? ? generate(:review_bodies) : comment }
    user
    book
  end
end

 

   

Rails factory bot Document

原文:https://www.cnblogs.com/lancgg/p/11647691.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!