How to eager-load fixture associations in Rails 6.1?

strict_loading_by_default was added to ActiveRecord 6.1. How can we eager load fixture associations to make tests pass once this flag is used?

class ApplicationRecord < ActiveRecord::Base
  self.strict_loading_by_default = true
end

# app/models/post.rb
class Post < ApplicationRecord
  belongs_to :author
end

# app/models/author.rb
class Author < ApplicationRecord; end

# test/fixtures/posts.yml
my_post:
  author: my_author

# test/fixtures/authors.yml
my_author: {}

# test/models/post_test.rb
class PostTest < ActiveSupport::TestCase
  test "post belongs to author" do
    post = posts(:my_post)

    assert post.author # Minitest::UnexpectedError: ActiveRecord::StrictLoadingViolationError: 
                       # `Author` called on `Post` is marked for strict_loading and cannot be lazily loaded.
  end
end

I think this is a bug. Can you please test if Ignore strict loading violations on instances loaded through fixtures by ghiculescu · Pull Request #40792 · rails/rails · GitHub fixes it for you?

1 Like

Thanks @ghiculescu, it works!

FYI that’s merged and on the 6-1-stable branch now.

Thanks @ghiculescu, good news :+1:

This works really well for us, thank you!