When using FactoryBot for generating random data in my RSpec tests for my Rails app, I had to keep prefixing my call to create with FactoryBot.

This caused my specs to look a bit cluttered.

trace = FactoryBot.create :trace
parent = FactoryBot.create :trace_field, trace: trace
child = FactoryBot.create :trace_field, trace: trace

It is possible to include the FactoryBot methods into RSpec so it will automatically find the methods from there.

To get that working, you could properly set up RSpec, as per the documentation, but if you didn’t you can add this to a file named spec/support/factory_bot.rb.

# spec/support/factory_bot.rb
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Also, make sure that you also uncomment this line in spec/rails_helper.rb so that RSpec includes any files you put in spec/support/.

Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f }

Now that we’ve fixed that we can remove the FactoryBot  prefix from the create calls to clean the whole thing up.

trace = create :trace
parent = create :trace_field, trace: trace
child = create :trace_field, trace: trace