FactoryBot is one of my favourite testing tools — I was a fan prior to
joining thoughtbot. It’s one of those tools I miss immediately when working
outside the Ruby ecosystem.
Recently I’ve been working on a Rails project that doesn’t need any database
persistence and therefore doesn’t use an object-relational mapper like
ActiveRecord. Instead data is fetched from an external JSON API and parsed into
value objects written in plain Ruby.
At the outset, the value objects needed for unit tests were manually written for
each example. As further attributes were added to the models this quickly became
tedious; the value objects created for previous tests also needed updating.
Fortunately FactoryBot can be used with plain Ruby objects, bringing all the
advantages of using factories in tests.
Side note: The examples use inline classes and factory definitions for brevity.
They’re also written as specs for self-proof each step works as intended.
Let’s begin with the simplest factory for a plain Ruby object:
it "supports building a PORO object" do class User attr_accessor :name end FactoryBot.define do factory :user do name "Amy" end end user = FactoryBot.build(:user) expect(user.name).to eq "Amy" end
The notable point here is the use of the
build strategy with the factory.
create strategy raises an exception:
NoMethodError: undefined method `save!' for #
` ` `