close

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.

全站熱搜
創作者介紹
創作者 Kolosek 的頭像
Kolosek

Kolosek

Kolosek 發表在 痞客邦 留言(0) 人氣()