← Back
factory-bot rails testing tools

Speed your tests by creating less DB objects

Maybe you already now it, but I've recently discovered that our old friend DatabaseCleaner is not needed anymore: since Rails 5.1 tests uses database transactions internally. Read here.

This is good for several reasons: you don't have to take care of object deletion. But more important: data from one test is absolutely isolated from each other.

This is not only safe, but enables parallel execution of tests 🏎️

Usually, the main bottleneck of tests is creating and destroying objects at database (even with transactions). And the problem is bigger when using factories like FactoryBot.

The problem with "create" in FactoryBot is that doesn't creates one object, but a bunch of them (because associations).

A possible solution is to use "build". There is a well known use case: test validations πŸ‘‡

expect(build(:template)).to be_valid)

But apart of this, the usefulness of build is very limited, mostly because the lack of associations.

Enter "build_stubbed":

It makes objects look like they’ve been persisted, including associations (...)

It doesn't work in all scenarios, but it should be your default option (instead of create) when writing new tests.

Read more πŸ‘‰ https://thoughtbot.com/blog/use-factory-girls-build-stubbed-for-a-faster-test From using this πŸ’Ž https://test-prof.evilmartians.io

πŸ––