Last Updated: December 07, 2021
· benburton

Taking the FactoryGirl out of FactoryGirl.create

I normally use FactoryGirl instead of directly using fixtures to instantiate models in my spec data. For example, it wouldn't be uncommon for me to write something similar to the following RSpec let statements to set up my test data:

let(:user) { FactoryGirl.create(:user) }
let(:blog_post) { FactoryGirl.create(:blog_post, user: user) }

I'd always thought it was a little verbose to write out FactoryGirl.create every time I made a call to the method. With this simple addition to the RSpec.configure block in your spec_helper.rb file:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods

You can stop calling FactoryGirl.create, and just call create:

let(:user) { create(:user) }
let(:blog_post) { create(:blog_post, user: user) }

To do the same in Cucumber, add the following to your env.rb file:


Now you can stop shouting at the FactoryGirl and save yourself some keystrokes!