JSON::ParserError: 767: unexpected token at 'MyText' (Rails & Minitest)

JSON::ParserError: 767: unexpected token at 'MyText' (Rails & Minitest)

当我 运行 在我的 Rails (5.2) 应用程序上进行测试时,我遇到了一些 JSON 解析器错误。这是一个例子:

ERROR["test_should_show_photo", Minitest::Result, 5.387737000361085] test_should_show_photo#Minitest::Result (5.39s) Minitest::UnexpectedError: ActionView::Template::Error: 767: unexpected token at 'MyText' app/views/photos/show.html.erb:2:in >_app_views_photos_show_html_erb___4241643449401419846_70111557791480' test/controllers/photos_controller_test.rb:27:in block in class:PhotosControllerTest'

错误发生在以下代码中调用@photo实例变量时的行:

require 'test_helper'

class PhotosControllerTest < ActionDispatch::IntegrationTest
  setup do
    @photo = photos(:one)
  end

  test "should get index" do
    get photos_url
    assert_response :success
  end

  test "should get new" do
    get new_photo_url
    assert_response :success
  end

  test "should create photo" do
    assert_difference('Photo.count') do
      post photos_url, params: { photo: { image_data: @photo.image_data } }
    end

    assert_redirected_to photo_url(Photo.last)
  end

  test "should show photo" do
    get photo_url(@photo)
    assert_response :success
  end

  test "should get edit" do
    get edit_photo_url(@photo)
    assert_response :success
  end

  test "should update photo" do
    patch photo_url(@photo), params: { photo: { image_data: @photo.image_data } }
    assert_redirected_to photo_url(@photo)
  end

  test "should destroy photo" do
    assert_difference('Photo.count', -1) do
      delete photo_url(@photo)
    end

    assert_redirected_to photos_url
  end
end

setup调用下面的yaml文件:

one:
  image_data: MyText (This must be where the problem is)

two:
  image_data: MyText

我假设这里的问题是 MyText 不是 JSON 语法,但我不知道如何更改它以便测试通过。

我想出了如何解决这个问题,我想 return 解决这个问题,以防它能帮助到其他人。

问题确实是默认脚手架生成的 .yml 文件无效 json。

我想到的解决方案是从我之前成功保存的数据库中复制并粘贴一条记录。我打开 Rails 控制台并查找有效的照片记录并将其用单引号引起来:

one:

image_data: '{"id":"164214a2b7a969102f90edadccaae62b.jpg","storage":"store","metadata":{"filename":"changes.jpg","size":24434,"mime_type":"image/jpeg"}}'

之后,所有失败的测试都通过了。