Tips for Using FactoryGirl Without an ORM

FactoryGirl 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 FactoryGirl can be used with plain Ruby objects, bringing all the
advantages of using factories in tests.

This exception occurs because the User class doesn’t implement #save!. When
using ActiveRecord this would have been defined by inheriting from
ApplicationRecord, which includes
ActiveRecord::Persistence.

The final piece of the FactoryGirl + plain Ruby objects puzzle is setting up
factory linting. Linting is typically run before the test suite to avoid a sea
of red test failures if a factory isn’t valid.

The output names the invalid factory and provides a stack trace, then the task
exits with a status of 1. The non-zero exit status is important — if this Rake
task is used in shell script with set -e or composed with other tasks — it’ll
skip the remaining steps and fail fast:

If you enjoyed this post, you might also like:

Want to level up your testing game?
Learn about testing Rails applications and TDD
in our new book
Testing Rails.
The book covers each type of test in depth,
intermediate testing concepts,
and anti-patterns that trip up even intermediate developers.