Skip to content
Mike Burns edited this page Apr 14, 2023 · 1 revision

If you're using Rails, add the following configuration to spec/support/factory_bot.rb and be sure to require that file in rails_helper.rb:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

If you're not using Rails:

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

  config.before(:suite) do
    FactoryBot.find_definitions
  end
end

FactoryBot::Syntax::Methods

Including FactoryBot::Syntax::Methods gives you access to build, build_list, create, create_list, and attributes_for directly in your tests, such as:

it "renders itself" do
  user = create(:user, articles: build_list(:article, 2)) # not FactoryBot.create or FactoryBot.build_list
  writer = build(:writer) # not FactoryBot.build
  
  user.render(writer)

  expect(writer.to_s).to eq("User with two articles")
end

find_definitions

The factory_bot-rails library will automatically find and load factory definitions during test runs by hooking into Rails loaders. Outside of Rails, you need to do that manually.