Search code examples
ruby-on-railsfactory-bot

How can I raise an error if my factory fails validation?


If I use FactoryBot to create a record, but it fails validation, it only returns an unsaved instance. Is there a way to make FactoryBot throw an error to help me debug issues early?

FactoryBot.create(:house, some_options)
=> #<House id: nil, ...>

The test will continue and will ultimately fail somewhere else because my object was not valid.

My first thought would be to create a trait and somehow default it to all factories, but I'm not seeing an easy way to do that.

trait :ensure_validity do
  before(:create) do |obj|
    raise StandardError unless obj.valid?
  end
end

Solution

  • Try the "bang" version of methods.

    house = FactoryBot.build(:house, options_hash)
    house.save!
    

    Unfortunately, FactoryBot doesn't come with a create! method, but ActiveRecord does.

    In Rails, you can cause ActiveRecord to throw errors when a record is invalid by using the :create! method instead of just the :create method.

    You could do

    House.create!(FactoryBot.attributes_for(:house, options_hash))