Rails PaperTrail 的 YAML 夹具错误 gem

Rails YAML Fixture Error with PaperTrail gem

我正在尝试创建一个 rails 夹具来测试一个控制器,该控制器获取 paper_trail gem (7.0.1) 的版本。但是,到目前为止,我一直无法在固定装置中填充任何版本来进行测试。而且,YAML 文件似乎没有 loading/is 破坏其他测试。这是我的 `versions.yml`` 文件的内容:

---
version_001:
  id: 1
  item_type: 'DistributionChannel'
  item_id: 1
  event: 'create'
  whodunnit: <%= User.find_by(email: 'user@example.com').id.to_s %>
  object: nil
  created_at: 2017-05-15 12:00:00.000000000 Z
  object_changes: '---\nid:\n- \n- 1\nprimary_channel:\n- \n- Best Buy\nsecondary_channel:\n- \n- ''\ncreated_at:\n- \n- 2017-05-15 12:00:00.000000000 Z\nupdated_at:\n- \n- 2017-05-15 12:00:00.000000000 Z\n'

该架构包含版本 table 以及适当的列 btw。

我最终通过将以下内容添加到 test_helper.rb 来加载夹具:

self.set_fixture_class versions: PaperTrail::Version

并且,具有以下 yaml 语法:

version_001:
  id: 1
  item_type: 'DistributionChannel'
  item_id: 1
  event: 'create'
  whodunnit: <%= ActiveRecord::FixtureSet.identify('user_example').to_s %>
  object: nil
  created_at: 2017-05-15 12:00:00
  object_changes: "---\nid:\n- \n- 1\nprimary_channel:\n- \n- Best Buy\nsecondary_channel:\n- \n- ''\ncreated_at:\n- \n- 2017-05-15 12:00:00.000000000 Z\nupdated_at:\n- \n- 2017-05-15 12:00:00.000000000 Z\n"

添加到 test_helper.rb 是必要的,因为版本 table 在 PaperTrail 中命名空间。我已经看到一些关于适当的 yaml 语法的相互矛盾的信息,所以我犹豫要解释我的理论为什么 yaml 语法有效(评论中的任何解释将不胜感激)。但是,希望这将有助于在使用 Minitest 和使用固定装置测试 paper_trail 时为某人指明正确的方向。

我遇到了类似的问题。当我没有使用 versions fixture(没有版本 fixture YAML 文件)时,这导致 versions table 在 rake db:fixtures:load 上没有被清除,所以这让我很困惑关于开发环境调试

为了避免这个问题,我引入了versions fixture 如下:

  1. 将 fixture 文件定位到 test/fixtures/paper_trail/versions.yml 以便 rake 任务自动加载它。
  2. 手写object_changes数据是一件非常繁琐的工作,所以让我们使用to_yaml方法生成它如下。创建 and/or 更新 AR 生成版本记录,以便在命令行生成 yaml 文件到 tmp/versions.yml:

    $ rails console
    irb> File.write('tmp/versions.yml', PaperTrail::Version.all.map{|v| v.attributes}.to_yaml)
    
  3. 编辑tmp/versions.yml如下,保存到test/fixtures/paper_trail/versions.yml:

    version_001:
      item_type:  DistributionChannel
      item:       distribution_001
      event:      create
      whodunnit:  ...
      created_at: 2017-12-27 02:25:33.000000000 Z
      object_changes: "... (keep as above to_yaml generated)..."
    
  4. 现在,运行rake db:fixtures:load!它应该将版本夹具加载到 PaperTrail::Version AR 并且 distribution_001 记录 .versions 方法应该包含它。

注意-1:上面的itemLabel Reference

NOTE-2: whodunnit 应该是一样的。参见 Fixture label interpolation