Skip to content

Instantly share code, notes, and snippets.

@mokevnin
Created December 6, 2023 19:01
Show Gist options
  • Save mokevnin/a787813ea5382f60ce34eeb76ca3fb52 to your computer and use it in GitHub Desktop.
Save mokevnin/a787813ea5382f60ce34eeb76ca3fb52 to your computer and use it in GitHub Desktop.
Rails fixture's monkey patch. It allows to preload fixtures before the tests and speed up the process
# frozen_string_literal: true
module Tests::FixtureLoader
extend ActiveSupport::Concern
included do
# Копипаста https://github.com/rails/rails/blob/844106efa9bc110260724d0fe503c321e7eb5b16/activerecord/lib/active_record/test_fixtures.rb#L210
# Можно улучшить
fixture_path = ActiveSupport::TestCase.fixture_path
fixture_set_names = Dir[::File.join(fixture_path, '{**,*}/*.{yml}')].uniq
fixture_set_names.map! { |f| f[fixture_path.to_s.size..-5].delete_prefix('/') }
fixture_set_names.each do |name|
# TODO оригинальные методы принимают на вход любое количество лейблов
define_method name.tr('/', '_') do |label|
id = ActiveRecord::FixtureSet.identify(label)
obj = name.singularize.classify.constantize.find_by(id: id)
raise "#{name}(:#{label}) has not found an object. Did you preload fixtures?" unless obj
obj
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment