vidhiya-saagar / spg2

🌕 Suraj Prakash Granth - Rails 7 Admin Application.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Setup FactoryBot

dsomel21 opened this issue · comments

Description

When writing unit tests, there's the concept of factories which are supposed to help us write tests.

They help us write tests because we will need to communicate with arbitrary database data to make sure our tests work.

Example

Most of the time our tests will communicate with the database.

# Without a fixture
it 'cannot save when missing `book_id`, `title`, and `number`' do
  expect { Chapter.create!(unrequired_chapter_fields) }.to raise_error(ActiveRecord::RecordInvalid)
end

However, there's gonna be some objects/data that we will need pretty often. That type of stuff is good to keep in fixtures.

What is FactoryBot

Rails has built in fixtures as well.... BUT... I prefer FactoryBot.

The reason being... when you define a fixture in Rails, they are added to the test database immediately. Where as FactoryBot will only create them when you call them

This is just my opinion though, but I find that with FactoryBot, you are jumping around the code a lot less, and instead, focused on writing good test.

Additional Resources