Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory Bot 5 on Rails 6 throws validation error when running build_stubbed factory

I have the following factory

function_groups.rb

FactoryBot.define do
  factory :function_group do
    factory :reports do
      # id 4
      name { "Reports" }
      functions {
        [find_or_create(:organization_report_function),
         find_or_create(:account_status_report_function)]
      }
    end
  end
end

functions.rb

FactoryBot.define do
  factory :function do
    factory :organization_report_function do
      name { "Org Report Function" }
      module_class { "organization_report_function" }
    end

    factory :account_status_report_function do
      name { "Acct Status Report" }
      module_class { "account_status_report_function" }
    end
  end
end

In my rails_helper.rb, my code looks like this

rails_helper.rb

require 'email_spec'
require 'capybara/rails'
require 'capybara/rspec'
require 'capybara-screenshot/rspec'

require 'capybara/poltergeist'

SERVER_PORT = 10000 + ENV.fetch('TEST_ENV_NUMBER', 0).to_i
Capybara.server = :puma, { Silent: true }
Capybara.server_port = SERVER_PORT
Capybara.javascript_driver = :poltergeist

options = { :js_errors => false, :debug => false, :phantomjs => Phantomjs.path, :phantomjs_logger => "/dev/null", timeout: 120 }

Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, options)
end

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

ActiveRecord::Migration.check_pending!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  # config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.render_views
  config.include Warden::Test::Helpers
  config.include EmailSpec::Helpers
  config.include EmailSpec::Matchers
  config.include LoginMacros
  config.include BaseRateMacros
  config.include Requests::JsonHelpers, type: :controller
  config.include Devise::Test::ControllerHelpers, type: :controller
  config.include LoginControllerHelpers, type: :controller
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)

  config.before(:each) do
   allow(FunctionGroup).to receive(:find_by_name).with("Reports").and_return(build_stubbed(:reports))
  end
  config.use_transactional_fixtures = false

  config.include FactoryBot::Syntax::Methods

  config.infer_base_class_for_anonymous_controllers = false

end

The main issue is when i try to run build_stubbed(:reports) i get an error

ActiveRecord::RecordInvalid Exception: Validation failed: Function group must exist

Not sure why because i thought build_stubbed should be able to create the parent record of the factory as well.

This was working well until i switched to Factory Bot 5 and Rails 6. Any clue as to how to fix this issue? Been struggling here for a while.

like image 374
Kingsley Simon Avatar asked Sep 16 '25 07:09

Kingsley Simon


1 Answers

Try checking the value of config.active_record.belongs_to_required_by_default.

What happened to me was before upgrading to Rails 6, I was not using config.load_defaults in config/application.rb, and I was relying on the old (before Rails 5.X) behavior of belongs_to associations not being required by default.

When I upgraded to Rails 6, I set config.load_defaults 6.0, which set belongs_to_required_by_default = true.

There are 2 ways to fix this:

Option 1: Add config.active_record.belongs_to_required_by_default = false to config/application.rb.

Option 2: Update your belongs_to lines in your models to have optional: true for associations that you don't want to be required.

Source: https://guides.rubyonrails.org/configuring.html#results-of-config-load-defaults

like image 50
Spencer Sullivan Avatar answered Sep 18 '25 21:09

Spencer Sullivan