1

我正在处理的 Rails 应用程序中的一个模型有一个 JSON 字段。这可以通过以下方式在夹具中创建:

first_record:
  name: "First Record"
  metadata:  <%= File.read("#{Rails.root}/test/fixtures/files/metadata/default.json") %>

...等等。但是,对于某些测试,元数据中需要默认值以外的值;这可以通过为每条记录设置单独的元数据文件来完成,或者在 YAML 文件中嵌入 JSON,但是记录很多,元数据也很多。因此,另一种选择是使用以下内容创建一个模块lib/modules

module TestMetadataHelper

  def create_metadata(args)
    metadata = JSON.parse(File.read("#{Rails.root}/test/fixtures/files/metadata/default.json"))
    args.each do |key, value|
      metadata[key] = value
    end
    metadata.to_json
  end

end

而且,为了在测试中可以访问它,这进入了 test_helper.rb:

ActiveRecord::FixtureSet.context_class.send :include, TestMetadataHelper

的,在固定装置:

metadata:  <%= create_metadata(field_to_change: "custom value") %>

使用这种方法测试运行得非常好,但是有一个问题:

$ RAILS_ENV=test bundle exec rake db:fixtures:load                                                               
rake aborted!
NoMethodError: undefined method `create_metadata' for #<#<Class:0x00007feeba246958>:0x00007feeba246890>

那么,如何通过加载我的模块来解决这个问题config/environments/test.rb

DEPRECATION WARNING: Initialization autoloaded the constant TestMetadataHelper.

Being able to do this is deprecated. Autoloading during initialization is going
to be an error condition in future versions of Rails.

Reloading does not reboot the application, and therefore code executed during
initialization does not run again. So, if you reload TestMetadataHelper, for example,
the expected changes won't be reflected in that stale Module object.

This autoloaded constant has been unloaded.

Please, check the "Autoloading and Reloading Constants" guide for solutions.

看过该指南后,我并不完全清楚如何最好地处理这种情况,所以如果有人有任何想法(例如如何解决这个警告,或者处理测试要求的更好方法),请发表评论。

4

0 回答 0