FactoryGirl (Bot) - create vs build vs build_stubb

If you are new to writing RSpec tests in Rails using FactoryGirl (bot), you can ask yourself what is the difference between createbuild and build_stubbed. In this article, we will do our best to help you understand them better.

Let's say we are testing a valid profile creation:

FactoryBot.define do
  factory :profile do
    user
    sequence(:name) { |n| "Name#{n}" }
  end
end

describe Profile, type: :model do
  it 'creates valid profile' do
    expect(FactoryBot.create(:profile)).to be_valid 
  end
end

FactoryBot.create(:profile) Will create profile object and all association for it. They will all be persisted in the database. Also,  it will trigger both model and database validations. Example test performance with create is:

create performance image

Note: after (: build) and after (: create) will be called after the factory is saved. Also, before (: create) will be called before the factory is saved.

On the other hand,  FactoryBot.build(:profile) will not save the object, but will still make requests to a database if the factory has associations. It will trigger validations only for associated objects. Example test performance with build  is:

build performance image

Note: after (: build) will be called after the factory is built.

FactoryBot.build_stubbed(:profile) It creates and assigns attributes to an object to make it behave like an instantiated object. It provides a fake id and created_at. Associations, if any, will be created via build_stubbed too. It will not trigger any validations. Example test performance with  build_stubbed  is:

build performance image

Note: after (: stub) will be called after the factory is stubbed via buildstubbed.

Keep in mind that this was a very simple test example. Better performance results are expected with more complex test suites.

Hopefully, it helped you better understand the differences between the ways to instantiate the objects when testing with FactoryBot.

Be sure to check our take on  Rspec let vs before and explanation on FactoryGirl associations. Also if you're totally new to RSpec, we have a guide to set it up.

Originally published on kolosek.com.

转载于:https://my.oschina.net/u/3772078/blog/1620777

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值